diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f75b5f3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules +build +npm-debug.log +.DS_Store +*.code-workspace \ No newline at end of file diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ae3eee2 --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +# AWSM +This is the second Version of the *AwesomeWaveSplineMachine*. It is a quite unique modular software synthesizer that utilizes dynamic *WaveSpline* synthesis. + +Click the link below to try the AWSM in your browser. + +🚀 [AWSM - AwesomeWaveSplineMachine](https://rnd7.github.io/awsm/dist/index.html) + +For more information consider one of the following links. + +📚 [User Guide](#user-guide) + +🏗 [Developer Guide](#developer-guide) + +🏛 [License](#license) + +# User guide + +[Back to top](#awsm) + +## Modes +Toggle between Database + +## Views + + +# Developer guide + +[Back to top](#awsm) + + +```bash +npm install +``` + +```bash +npm run build +``` + +```bash +npm run serve +``` + + +# License + +[Back to top](#awsm) + +Feel free to use this tool to make music or to test the limits of your speakers. I encourage this. When redistributing the software, be sure to understand the underlying license. Since I'm donating a considerable amount of my time to the opensource community, it's important to me that everything that builds on this is also available to everyone. + +This project is licensed under the GNU General Public License v3.0 + +Copyright (C) 2024 C. Nicholas Schreiber + +See [COPYING](https://rnd7.github.io/awsm-mkii/COPYING) for the license text or contact me for more information. + +The license applies to every file within this repository even if not explicitly stated within the source code of every module. + +Official GNU license page: [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.html) diff --git a/dist/audio/audio-metrics-analyzer.js b/dist/audio/audio-metrics-analyzer.js new file mode 100644 index 0000000..8887a55 --- /dev/null +++ b/dist/audio/audio-metrics-analyzer.js @@ -0,0 +1,45 @@ + +export default class AudioMetricsAnalyzer { + + #audioContext + #analyserNode + #audioMetrics + #source + #lastFrame = 0 + constructor(audioContext) { + this.#audioContext = audioContext + this.#analyserNode = this.#audioContext.createAnalyser() + this.#analyserNode.fftSize = 2048 + this.#analyserNode.smoothingTimeConstant = 0.8 + } + + connect(source) { + if (this.#source) this.#source.disconnect(this.#analyserNode) + this.#source = source + this.#source.connect(this.#analyserNode) + } + + update() { + const now = Date.now() + if (!this.#audioMetrics || this.#lastFrame >= now-10) return + this.#lastFrame = now + this.#analyserNode.getByteTimeDomainData(this.#audioMetrics.frame) + } + + set audioMetrics(value) { + this.#audioMetrics = value + this.#audioMetrics.frame = new Uint8Array(this.#analyserNode.frequencyBinCount) + this.#audioMetrics.callback = this.update.bind(this) + } + + get audioMetrics() { + return this.#audioMetrics + } + + destroy() { + this.#source.disconnect(this.#analyserNode) + this.#audioMetrics = null + this.#audioContext = null + this.#analyserNode = null + } +} \ No newline at end of file diff --git a/dist/audio/audio-squeeze-processor.js b/dist/audio/audio-squeeze-processor.js new file mode 100644 index 0000000..b16fc04 --- /dev/null +++ b/dist/audio/audio-squeeze-processor.js @@ -0,0 +1,141 @@ +import interpolateLinear from "../math/interpolate-linear.js" + +class AudioSqueezeProcessor extends AudioWorkletProcessor { + static get parameterDescriptors() { + return [{ + name: 'threshold', // threshold (0-1 normalized) + defaultValue: 0.5, + minValue: 0.0, + maxValue: 1.0, + automationRate: "a-rate", + }, { + name: 'scale', // scale + defaultValue: 1, + minValue: 0, + maxValue: 10, + automationRate: "a-rate", + }, { + name: 'potential', // loudness factor + defaultValue: 0.0, + minValue: 0, + maxValue: 1, + automationRate: "a-rate", + }, { + name: 'inputs', + defaultValue: 0, + minValue: 0, + maxValue: 128, + automationRate: "k-rate", + }] + } + + #bufferIndex = 0 + + #targetPeak = 0 + #peak = 0 + #peakIncrement = 0 + #peakTime = 0 + + #buffer = new Float32Array(512) + #output = new Float32Array(128) + #delay = 512 + + constructor(...args) { + super(...args) + this.port.onmessage = (message) => { + if (message.data.type === "destroy") { + this.onDestroy() + } + } + } + + onDestroy() { + this.port.onmessage = null + this.port.close() + } + + process(inputs, outputs, parameters) { + for (let outputIndex = 0; outputIndex < outputs.length; outputIndex++) { + const output = outputs[outputIndex] + for (let channelIndex = 0; channelIndex < output.length; channelIndex++) { + const channel = output[channelIndex] + if (outputIndex == 0 && channelIndex == 0) { + if (channel.length != this.#buffer.length) { + this.#output = new Float32Array(channel.length) + } + if (this.#buffer.length != this.#delay) { + this.#buffer = new Float32Array(this.#delay) + } + } + for (let sample = 0; sample < channel.length; sample++) { + if (channelIndex == 0 && outputIndex == 0) { + + let amplitude = 0 + for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) { + const input = inputs[inputIndex] + if (input.length) amplitude += input[channelIndex][sample] + } + + this.#buffer[this.#bufferIndex] = amplitude + + let magnitude = Math.abs(amplitude) + + if (magnitude >= this.#targetPeak *.9) { + this.#peakTime = 0 + } + if (magnitude >= this.#targetPeak) { + this.#targetPeak = magnitude + } + this.#peakIncrement = (8 * this.#targetPeak) / this.#delay // min value to get from -peak to peak within delay + + if (this.#peak - this.#peakIncrement > this.#targetPeak) { + this.#peak -= this.#peakIncrement + } else if (this.#peak + this.#peakIncrement < this.#targetPeak) { + this.#peak += this.#peakIncrement + } else { + this.#peak = this.#targetPeak + } + + let liveAmplitude = this.#buffer[(this.#bufferIndex+1)%this.#buffer.length] || 0 + let liveMagnitude = Math.abs(liveAmplitude) + let liveSign = Math.sign(liveAmplitude) + const overdrive = parameters.potential.length>1?parameters.potential[sample]:parameters.potential[0] + const threshold = (parameters.threshold.length>1?parameters.threshold[sample]:parameters.threshold[0]) * .99 + const scale = parameters.scale.length>1?parameters.scale[sample]:parameters.scale[0] + let out = 0 + let scaledMax = Math.max( + threshold + (1-threshold) * scale, + threshold + (1-threshold) * .5 + ) + + if (this.#peak > 0) { + out = liveMagnitude / this.#peak + if (out > threshold) { + let rel = out - threshold + let scaledRel = rel * scale + out = threshold + interpolateLinear(rel, scaledRel, rel/(1-threshold)) + } + } + out /= scaledMax + if (this.#peak < 1) out = interpolateLinear(out * this.#peak, out, overdrive) + + this.#output[sample] = out * liveSign * .9999 + + if (this.#peakTime > this.#delay ) { + this.#targetPeak = this.#targetPeak * .99999 + } + + this.#bufferIndex = (this.#bufferIndex+1)%this.#buffer.length + this.#peakTime++ + + } + channel[sample] = this.#output[sample] + + + } + } + } + return true + } +} +registerProcessor("audio-squeeze-processor", AudioSqueezeProcessor); \ No newline at end of file diff --git a/dist/audio/channel-manager.js b/dist/audio/channel-manager.js new file mode 100644 index 0000000..60f0ea4 --- /dev/null +++ b/dist/audio/channel-manager.js @@ -0,0 +1,190 @@ +import watch from "../glue/watch.js" +import unwatch from "../glue/unwatch.js" +import Channel from "../model/channel.js" +import VoiceManager from "./voice-manager.js" +import Dynamics from "../model/dynamics.js" +import Voice from "../model/voice.js" +import AudioMetricsAnalyzer from "./audio-metrics-analyzer.js" + +export default class ChannelManager { + #audioContext + #channel + #voiceMap = new Map() + #gainNode + #mix = 0 + #inputs + #potentialParam + #dynamics + #thresholdParam + #scaleParam + #channelGainChangeTime = 1/100 + #audioMetricsAnalyzer + #soloBus + #releaseTimeout + #potentialChangeTime = 1/10 + + constructor(audioContext, channel) { + this.#audioContext = audioContext + this.#gainNode = this.#audioContext.createGain() + this.#gainNode.gain.value = 0 + + this.#dynamics = new AudioWorkletNode(this.#audioContext, 'audio-squeeze-processor') + this.#inputs = this.#dynamics.parameters.get('inputs') + this.#potentialParam = this.#dynamics.parameters.get('potential') + this.#thresholdParam = this.#dynamics.parameters.get('threshold') + this.#scaleParam = this.#dynamics.parameters.get('scale') + this.#dynamics.connect(this.#gainNode) + + this.#audioMetricsAnalyzer = new AudioMetricsAnalyzer(this.#audioContext) + this.#audioMetricsAnalyzer.connect(this.#gainNode) + + watch(this, "channel", this.#onChannelChange.bind(this)) + if (channel) this.channel = channel + + } + + set channel(value) { + this.#channel = value + this.#audioMetricsAnalyzer.audioMetrics = this.#channel.audioMetrics + this.#updateDynamics() + this.#update() + } + + get channel() { + return this.#channel + } + + set mix(value) { + this.#mix = value + this.#update() + } + + get mix() { + return this.#mix + } + + get audioMetrics() { + return this.#audioMetricsAnalyzer + } + + pause() { + this.#voiceMap.forEach((voiceManager)=>{ + voiceManager.pause() + }) + } + + play() { + this.#voiceMap.forEach((voiceManager)=>{ + voiceManager.play() + }) + } + + connect(destination) { + this.#gainNode.connect(destination) + } + + set soloBus(value) { + this.#soloBus = value + this.#voiceMap.forEach((voiceManager) => { + voiceManager.soloBus = this.#soloBus + }) + } + + get soloBus() { + return this.#soloBus + } + + sync() { + this.#voiceMap.forEach((voiceManager) => { + voiceManager.sync() + }) + } + + zeroAll(id, found=false) { + if (this.#channel.id === id) found = true + this.#voiceMap.forEach((voiceManager) => { + voiceManager.zeroAll(id, found) + }) + } + + #onChannelChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + ) { + this.#updateDynamics() + + } else if (signal.path.length == 1){ + this.#update() + } + } + + #updateDynamics() { + this.#thresholdParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#thresholdParam.setValueAtTime(this.#thresholdParam.value, this.#audioContext.currentTime); + this.#thresholdParam.linearRampToValueAtTime( this.#channel.dynamics.threshold, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#scaleParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#scaleParam.setValueAtTime(this.#scaleParam.value, this.#audioContext.currentTime); + this.#scaleParam.linearRampToValueAtTime( this.#channel.dynamics.scale, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#potentialParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#potentialParam.setValueAtTime(this.#potentialParam.value, this.#audioContext.currentTime); + this.#potentialParam.linearRampToValueAtTime( this.#channel.dynamics.potential, this.#audioContext.currentTime + this.#potentialChangeTime); + + } + + #onReleaseTimeout() { + if (this.#channel.state === Channel.RELEASE) { + this.#channel.state = Channel.DELETE + } + } + + #update() { + this.#inputs.setValueAtTime(this.#channel.voices.length, this.#audioContext.currentTime) + if (this.#channel.state === Channel.ACTIVE) { + clearTimeout(this.#releaseTimeout) + this.#channel.voices.forEach(voice => { + if (voice.state === Voice.DELETE) { + if (this.#voiceMap.has(voice.id)) { + let voiceManager = this.#voiceMap.get(voice.id) + voiceManager.destroy() + this.#voiceMap.delete(voice.id) + } + } else { + if (!this.#voiceMap.has(voice.id)) { + const voiceManager = new VoiceManager(this.#audioContext, voice) + voiceManager.connect(this.#dynamics) + voiceManager.soloBus = this.#soloBus + this.#voiceMap.set(voice.id, voiceManager) + } + } + }) + let gainMultiplier = 1 + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime) + this.#gainNode.gain.linearRampToValueAtTime( + this.#channel.gain * gainMultiplier * this.#mix, + this.#audioContext.currentTime + this.#channelGainChangeTime + ) + } else if (this.#channel.state === Channel.TRIGGER_RELEASE) { + clearTimeout(this.#releaseTimeout) + this.#channel.state = Channel.RELEASE + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime) + this.#gainNode.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#channel.release) + this.#releaseTimeout = setTimeout(()=>{this.#onReleaseTimeout()}, this.channel.release * 1000) + } + } + + destroy() { + unwatch(this, "channel") + this.#voiceMap.forEach((voiceManager, key) => { + voiceManager.destroy() + }) + this.#voiceMap = null + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.disconnect() + this.#audioContext = null + this.#channel = null + } +} \ No newline at end of file diff --git a/dist/audio/session-manager.js b/dist/audio/session-manager.js new file mode 100644 index 0000000..f03885a --- /dev/null +++ b/dist/audio/session-manager.js @@ -0,0 +1,282 @@ +import watch from "../glue/watch.js" +import calculatePoleValue from "../math/calculate-pole-value.js" +import Channel from "../model/channel.js" +import Dynamics from "../model/dynamics.js" +import Session from "../model/session.js" +import AudioMetricsAnalyzer from "./audio-metrics-analyzer.js" +import ChannelManager from "./channel-manager.js" + +export default class SessionManager { + #audioContext + #session = new Session() + #channels = [] + #ready = false + #scheduled = false + #gainNode + #masterNode + #channelMap = new Map() + #dynamicLimit + #thresholdParam + #scaleParam + #potentialParam + #audioMetricsAnalyzer + #outNode + #powerUpTime = 2 + #syncInterval + #syncRate = 1000/30 + #soloBus + #mainBus + constructor(session) { + watch(this, "session", this.#onSessionChange.bind(this)) + if (session) this.session = session + } + + + async inititialize() { + this.#audioContext = new AudioContext() + await this.#audioContext.audioWorklet.addModule(`audio/wave-spline-processor.js?a=${Math.random()}`).catch(console.error) + await this.#audioContext.audioWorklet.addModule(`audio/audio-squeeze-processor.js?a=${Math.random()}`).catch(console.error) + + // preglow to remove initial latency + const wsp = new AudioWorkletNode(this.#audioContext, 'wave-spline-processor') + const asp = new AudioWorkletNode(this.#audioContext, 'audio-squeeze-processor') + + + + this.#dynamicLimit = new AudioWorkletNode(this.#audioContext, 'audio-squeeze-processor') + this.#thresholdParam = this.#dynamicLimit.parameters.get('threshold') + this.#scaleParam = this.#dynamicLimit.parameters.get('scale') + this.#potentialParam = this.#dynamicLimit.parameters.get('potential') + + this.#gainNode = this.#audioContext.createGain() + this.#gainNode.gain.value = 0 + + this.#masterNode = this.#audioContext.createGain() + this.#masterNode.gain.value = 0 + + this.#outNode = this.#audioContext.createGain() + this.#outNode.gain.value = 0 + + + this.#mainBus = this.#audioContext.createGain() + this.#mainBus.connect(this.#gainNode) + + this.#soloBus = this.#audioContext.createGain() + this.#soloBus.connect(this.#gainNode) + + this.#gainNode.connect(this.#audioContext.destination) + + this.#dynamicLimit.connect(this.#masterNode) + this.#masterNode.connect(this.#outNode) + + setTimeout(()=>{ + this.#outNode.connect(this.#mainBus) + + this.#powerUp() + }, 1000) + + this.#audioMetricsAnalyzer = new AudioMetricsAnalyzer(this.#audioContext) + this.#audioMetricsAnalyzer.connect(this.#masterNode) + + this.#ready = true + if (this.#scheduled) { + this.#update() + this.#updatePotential() + this.#updateDynamics() + } + } + + set session(value) { + this.#session = value + if (this.#session) { + this.#audioMetricsAnalyzer.audioMetrics = this.#session.audioMetrics + this.solo(this.#session.solo) + } + this.#update() + this.#updatePotential() + this.#updateDynamics() + } + + #powerUp() { + + this.#syncInterval = setInterval(()=>{ + this.sync() + }, this.#syncRate) + this.#outNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#outNode.gain.setValueAtTime(this.#outNode.gain.value, this.#audioContext.currentTime); + this.#outNode.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#powerUpTime) + } + + sync() { + this.#channelMap.forEach((channelManager)=>{ + channelManager.sync() + }) + } + + get session() { + return this.#session + } + + get audioContext() { + return this.#audioContext + } + + get audioMetrics() { + return this.#audioMetricsAnalyzer + } + + #onSessionChange(signal) { + if (signal.path[0].property === "solo") { + this.solo(this.#session.solo) + } else if ( + signal.path[0].origin instanceof Dynamics + ) { + this.#updateDynamics() + + } else if (signal.path.length <= 2){ + this.#update() + this.#updatePotential() + } + } + + #soloTime = 1/100 + + solo(id) { + if (id) { + this.#mainBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#mainBus.gain.setValueAtTime(this.#mainBus.gain.value, this.#audioContext.currentTime); + this.#mainBus.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#soloTime) + + this.#soloBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#soloBus.gain.setValueAtTime(this.#soloBus.gain.value, this.#audioContext.currentTime); + this.#soloBus.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#soloTime) + } else { + this.#soloBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#soloBus.gain.setValueAtTime(this.#soloBus.gain.value, this.#audioContext.currentTime); + this.#soloBus.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#soloTime) + + this.#mainBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#mainBus.gain.setValueAtTime(this.#mainBus.gain.value, this.#audioContext.currentTime); + this.#mainBus.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#soloTime) + } + } + + stopAll() { + if (!this.#ready) return Promise.resolve() + return new Promise((resolve, reject)=> { + this.#ready = false + this.#scheduled = false + this.#masterNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#masterNode.gain.setValueAtTime(this.#masterNode.gain.value, this.#audioContext.currentTime); + this.#masterNode.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#playPauseTime) + setTimeout(()=>{ + for (let [id, channelManager] of this.#channelMap) { + channelManager.destroy() + this.#channelMap.delete(id) + } + this.#ready = true + resolve() + if (this.#scheduled) this.#update() + }, this.#playPauseTime * 1000 ) + }) + + } + + #updateDynamics() { + if (!this.#ready) return this.#scheduled = true + if (!this.#session) return + + this.#thresholdParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#thresholdParam.setValueAtTime(this.#thresholdParam.value, this.#audioContext.currentTime); + this.#thresholdParam.linearRampToValueAtTime( this.#session.dynamics.threshold, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#scaleParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#scaleParam.setValueAtTime(this.#scaleParam.value, this.#audioContext.currentTime); + this.#scaleParam.linearRampToValueAtTime( this.#session.dynamics.scale, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#potentialParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#potentialParam.setValueAtTime(this.#potentialParam.value, this.#audioContext.currentTime); + this.#potentialParam.linearRampToValueAtTime( this.#session.dynamics.potential, this.#audioContext.currentTime + this.#potentialChangeTime); + + } + + #playPauseTime = 1/10 + #potentialChangeTime = 1/10 + #playPauseTimeout + + + + #update() { + if (!this.#ready) return this.#scheduled = true + if (!this.#session) return + if (this.#session.state === Session.TRIGGER_PLAY) { + clearTimeout(this.#playPauseTimeout) + this.#session.state = Session.PLAY + this.#channelMap.forEach((channelManager)=>{ + channelManager.play() + }) + this.#masterNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#masterNode.gain.setValueAtTime(this.#masterNode.gain.value, this.#audioContext.currentTime) + this.#masterNode.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#playPauseTime) + this.#playPauseTimeout = setTimeout(()=>{ + this.#session.state = Session.PLAYING + }, this.#playPauseTime * 1000) + } else if (this.#session.state === Session.TRIGGER_PAUSE) { + clearTimeout(this.#playPauseTimeout) + this.#session.state = Session.PAUSE + this.#masterNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#masterNode.gain.setValueAtTime(this.#masterNode.gain.value, this.#audioContext.currentTime); + this.#masterNode.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#playPauseTime) + + this.#playPauseTimeout = setTimeout(()=>{ + this.#channelMap.forEach((channelManager)=>{ + channelManager.pause() + }) + this.#session.state = Session.PAUSED + }, this.#playPauseTime * 1000) + + } + this.#session.channels.forEach(channel => { + if (channel.state === Channel.DELETE) { + if (this.#channelMap.has(channel.id)) { + let channelManager = this.#channelMap.get(channel.id) + channelManager.destroy() + this.#channelMap.delete(channel.id) + } + } else { + if (!this.#channelMap.has(channel.id)) { + let channelManager = new ChannelManager(this.#audioContext, channel) + channelManager.connect(this.#dynamicLimit) + channelManager.soloBus = this.#soloBus + this.#channelMap.set(channel.id, channelManager) + } + } + + }) + for (let i = 0; i{ + channelManager.zeroAll(id, found) + }) + } + + #updatePotential() { + if (!this.#ready) return this.#scheduled = true + if (!this.#session) return + let potentialFactor = 1 + + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime); + this.#gainNode.gain.linearRampToValueAtTime( this.#session.main * potentialFactor, this.#audioContext.currentTime + this.#potentialChangeTime); + + + } +} \ No newline at end of file diff --git a/dist/audio/voice-manager.js b/dist/audio/voice-manager.js new file mode 100644 index 0000000..2da8c2b --- /dev/null +++ b/dist/audio/voice-manager.js @@ -0,0 +1,206 @@ +import clone from "../data/clone.js" +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Voice from "../model/voice.js" +import syncVoice from "../wave-spline/sync-voice.js" + +export default class VoiceManager { + #audioContext + #voice + #processor + #gainNode + #envelope + #envelopeTimeout + #gainChangeTime = 1/100 + #soloBus + #outBus + #soloConnected = false + + constructor(audioContext, voice) { + this.#audioContext = audioContext + this.#gainNode = this.#audioContext.createGain() + this.#gainNode.gain.value = 0 + this.#envelope = this.#audioContext.createGain() + this.#envelope.gain.value = 0 + this.#processor = new AudioWorkletNode(this.#audioContext, 'wave-spline-processor') + this.#processor.port.onmessage = (msg) => { + if (msg.data.type === "sync") { + syncVoice(this.voice, msg.data.voice) + } + } + + this.#processor.connect(this.#gainNode) + this.#gainNode.connect(this.#envelope) + + watch(this, "voice", this.#onVoiceChange.bind(this)) + if (voice) this.voice = voice + + } + + #onVoiceChange(signal) { + if (signal.path[0].property === "bus") { + this.#updateBus() + } else if (signal.path[0].property === "state") { + this.#updateState() + } else if (signal.path[0].origin === this.voice && signal.path[0].property === "gain") { + this.#updateGain() + } else if ( + signal.path[0].property !== "phase" + && signal.path[0].property !== "name" + && signal.path[0].property !== "lengthDriver" + && signal.path[0].property !== "gridX" + && signal.path[0].property !== "gridY" + && signal.path[0].property !== "viewZoom" + && signal.path[0].property !== "viewPosition" + ) { + this.#update() + } + } + + set voice(value) { + this.#voice = value + this.#updateBus() + this.#updateState() + this.#updateGain() + this.#update() + } + + get voice() { + return this.#voice + } + + pause() { + this.#processor.port.postMessage({ + type: "pause" + }) + } + + play() { + this.#processor.port.postMessage({ + type: "play" + }) + } + + sync() { + this.#processor.port.postMessage({ + type: "sync" + }) + } + + zeroAll(id, found=false) { + if (this.#voice.id === id) found = true + let updateRequired = false + const zeroRecursive = (osc, id, found=false) => { + if (osc.id === id) found = true + if (found) { + updateRequired = true + osc.phase = 0 + } + if (osc.fm) zeroRecursive(osc.fm, id, found) + if (osc.am) zeroRecursive(osc.am, id, found) + if (osc.em) zeroRecursive(osc.em, id, found) + if (osc.sx) zeroRecursive(osc.sx, id, found) + if (osc.sy) zeroRecursive(osc.sy, id, found) + if (osc.gain) zeroRecursive(osc.gain, id, found) + if (osc.transpose) zeroRecursive(osc.transpose, id, found) + } + zeroRecursive(this.#voice.oscillator, id, found) + if (updateRequired) this.#update(false) + } + + connect(destination) { + this.#outBus = destination + this.#envelope.connect(this.#outBus) + } + + set soloBus(value) { + this.#soloBus = value + this.#updateBus() + } + + get soloBus() { + return this.#soloBus + } + + #onEnvelopeTimeout() { + if (!this.#voice) return + if (this.#voice.state === Voice.RELEASE) { + this.#voice.state = Voice.IDLE + } else if (this.#voice.state === Voice.DELETE_RELEASE) { + this.#voice.state = Voice.DELETE + } else if (this.#voice.state === Voice.ATTACK) { + this.#voice.state = Voice.SUSTAIN + } + this.#envelopeTimeout = null + } + + #updateBus() { + if (this.#voice && this.#voice.bus === "main" && this.#outBus) { + if (this.#soloConnected) { + this.#envelope.disconnect(this.#soloBus) + this.#soloConnected = false + } + } else if (this.#voice && this.#voice.bus === "solo" && this.#soloBus) { + if (!this.#soloConnected) { + this.#envelope.connect(this.#soloBus) + this.#soloConnected = true + } + } + } + + #updateState() { + + if (this.#voice.state === Voice.TRIGGER_ATTACK) { + clearTimeout(this.#envelopeTimeout) + this.#voice.state = Voice.ATTACK + this.#envelope.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#envelope.gain.setValueAtTime(this.#envelope.gain.value, this.#audioContext.currentTime) + this.#envelope.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#voice.attack) + this.#envelopeTimeout = setTimeout(()=>{this.#onEnvelopeTimeout()}, this.#voice.attack * 1000) + } else if (this.#voice.state === Voice.TRIGGER_RELEASE) { + clearTimeout(this.#envelopeTimeout) + this.#voice.state = Voice.RELEASE + this.#envelope.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#envelope.gain.setValueAtTime(this.#envelope.gain.value, this.#audioContext.currentTime) + this.#envelope.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#voice.release) + this.#envelopeTimeout = setTimeout(()=>{this.#onEnvelopeTimeout()}, this.#voice.release * 1000) + } else if (this.#voice.state === Voice.TRIGGER_DELETE) { + clearTimeout(this.#envelopeTimeout) + this.#voice.state = Voice.DELETE_RELEASE + this.#envelope.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#envelope.gain.setValueAtTime(this.#envelope.gain.value, this.#audioContext.currentTime) + this.#envelope.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#voice.release) + this.#envelopeTimeout = setTimeout(()=>{this.#onEnvelopeTimeout()}, this.#voice.release * 1000) + } + } + + #updateGain() { + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime) + this.#gainNode.gain.linearRampToValueAtTime(this.#voice.gain, this.#audioContext.currentTime + this.#gainChangeTime) + } + + #update(sync = true) { + this.#processor.port.postMessage({ + type: "voice", + voice: clone(this.#voice), + sync + }) + + + } + + destroy() { + unwatch(this, "voice") + this.#voice = null + this.#processor.port.postMessage({ + type: "destroy" + }) + + this.#processor.port.close() + this.#processor.disconnect() + this.#processor = null + this.#audioContext = null + + } +} \ No newline at end of file diff --git a/dist/audio/wave-spline-processor.js b/dist/audio/wave-spline-processor.js new file mode 100644 index 0000000..945d55d --- /dev/null +++ b/dist/audio/wave-spline-processor.js @@ -0,0 +1,309 @@ +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +var __webpack_exports__ = {}; + +;// CONCATENATED MODULE: ./src/math/interpolate-linear.js +function interpolateLinear(a, b, q) { + return a + (b - a) * q; +} +;// CONCATENATED MODULE: ./src/math/normalize.js +function normalize(value, {min = 0, max = 1} = {}) { + return value * (max-min) + min +} +;// CONCATENATED MODULE: ./src/math/calculate-q.js +function calcQ(a, b, x) { + const dx = (1 + (b - a)) % 1 + const xn = ((1 + (x - a)) % 1) / dx + return xn +} +;// CONCATENATED MODULE: ./src/math/interpolate-exponential.js + + +function interpolateExponential(a, b, e, q) { + if (e == 1) return interpolateLinear(a, b, q) // is linear + if (q < .5) return interpolateLinear(a, b, Math.pow((q * 2), e) / 2) + return interpolateLinear(a, b, 1 - Math.pow(((1 - q) * 2), e) / 2) +} +;// CONCATENATED MODULE: ./src/math/quantize.js +function quantize(value, quantize = Number.MAX_SAFE_INTEGER, threshold = 0, override = false) { + if (override || quantize >= Number.MAX_SAFE_INTEGER) return value + let t = threshold * .5 + .5 + return ((t + value * quantize) | 0) / quantize +} +;// CONCATENATED MODULE: ./src/wave-spline/find-pair.js +function findPair(points, x) { + const len = points.length + if (!len) return [] + if (len == 1) return [points[0], points[0]] + let a = len-1 + let b = 0 + for (let i = 0; i x ) { + b = i + break + } + a = i + } + return [points[a], points[b]] +} +;// CONCATENATED MODULE: ./src/math/compare-float.js +function compareFloat(a,b, tolerance = 1e-8) { + return Math.abs(a - b) < tolerance +} +;// CONCATENATED MODULE: ./src/wave-spline/transform-wave-spline-point.js +function transformWaveSplinePoint(point, cx=.5, cy=.5, sx=1, sy=1, rx=1, ry=1) { + if (sx == 1 && sy == 1) return point + if (point.x < cx - rx || point.x > cx + rx) return point + return { + x: ((point.x-cx)*sx+cx), + y: ((point.y-cy)*sy+cy), + e: point.e + } +} +;// CONCATENATED MODULE: ./src/wave-spline/process-wave-spline-points.js + + + +function processWaveSplinePoints(points, cx=.5, cy=.5, sx=1, sy=1, rx=1, ry=1) { + + const len = points.length + let out = [] + let point = {x: -1, y: 0, e: 0} + let x = -1 + let y = 0 + let e = 0 + let stackCount = 0 + let cur + for (let i = 0; i { + if (message.data.type === "voice") { + this.onVoiceData(message.data.voice, message.data.sync) + } else if (message.data.type === "update") { + this.onVoiceUpdate(message.data.voice) + } else if (message.data.type === "destroy") { + this.onDestroy() + } else if (message.data.type === "sync") { + this.port.postMessage({type: "sync", voice: this.#voices[this.#voices.length-1]}) + } else if (message.data.type === "play") { + this.#play = true + } else if (message.data.type === "pause") { + this.#play = false + } + } + + } + + onVoiceData(voice, sync) { + if (this.#voices.length>2)this.#voices.pop() + if (sync && this.#voices.length) syncVoice(voice, this.#voices[this.#voices.length-1]) + this.#voices.push(voice) + } + + onVoiceUpdate(value) { + this.#voices.forEach((voice=>{ + Object.assign(voice, value) + })) + } + + onDestroy() { + this.port.onmessage = null + this.port.close() + this.#voices = [] + this.#transition = 0 + this.#keepAlive = false + } + + process(inputs, outputs, parameters) { + for (let outputIndex = 0; outputIndex < outputs.length; outputIndex++) { + const output = outputs[outputIndex] + for (let channelIndex = 0; channelIndex < output.length; channelIndex++) { + const channel = output[channelIndex] + if (outputIndex == 0 && channelIndex == 0 && channel.length != this.#buffer.length) this.#buffer = new Float32Array(channel.length) + for (let frame = 0; frame < channel.length; frame++) { + if (channelIndex == 0 && outputIndex == 0) { + let val = 0 + if (this.#play) { + if (this.#voices.length == 1) { + val = solveVoice(sampleRate, this.#voices[0]) + + } else if (this.#voices.length >= 2) { + const transitionFrames = Math.min(this.#maxTransitionTime, this.#voices[0].oscillator.length) * sampleRate + const q = this.#transition / transitionFrames + val = interpolateLinear( + solveVoice(sampleRate, this.#voices[0]), + solveVoice(sampleRate, this.#voices[1]), + q + ) + if (this.#voices.length >= 3) { + solveVoice(sampleRate, this.#voices[2]) + } + this.#transition++ + if (this.#transition >= transitionFrames) { + this.#voices.shift() + this.#transition = 0 + } + } + } + + this.#buffer[frame] = val + } + channel[frame] = this.#buffer[frame] + + } + } + } + + return this.#keepAlive + } +} +registerProcessor("wave-spline-processor", WaveSplineProcessor); +/******/ })() +; \ No newline at end of file diff --git a/dist/color/hsl-to-rgb.js b/dist/color/hsl-to-rgb.js new file mode 100644 index 0000000..e8c58ff --- /dev/null +++ b/dist/color/hsl-to-rgb.js @@ -0,0 +1,10 @@ +/* +Based on https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion +posted by Kamil Kiełczewski +input: h as an angle in [0,360] and s,l in [0,1] - output: r,g,b in [0,1] +*/ +export default function hslToRgb({h = 0, s = 0, l = 0} = {}) { + const a = s*Math.min(l,1-l) + const f = (n,k=(n+h/30)%12) => l - a * Math.max(Math.min(k-3,9-k,1),-1) + return {r: f(0), g: f(8), b: f(4)} +} \ No newline at end of file diff --git a/dist/color/hsv-to-rgb.js b/dist/color/hsv-to-rgb.js new file mode 100644 index 0000000..cdc90b8 --- /dev/null +++ b/dist/color/hsv-to-rgb.js @@ -0,0 +1,9 @@ +/* +Based on https://stackoverflow.com/questions/17242144/javascript-convert-hsb-hsv-color-to-rgb-accurately/54024653#54024653 +posted by Kamil Kiełczewski +input: h in [0,360] and s,v in [0,1] - output: r,g,b in [0,1] +*/ +export default function hsvToRgb({h = 0, s = 0, v = 0} = {}) { + const f = (n,k=(n+h/60)%6) => v - v * s * Math.max(0, Math.min(k, 4 - k, 1)) + return {r: f(5), g: f(3), b: f(1)}; +} \ No newline at end of file diff --git a/dist/color/rgb-to-css.js b/dist/color/rgb-to-css.js new file mode 100644 index 0000000..955ff00 --- /dev/null +++ b/dist/color/rgb-to-css.js @@ -0,0 +1,3 @@ +export default function rgbToCss({r = 0, g = 0, b = 0} = {}) { + return `rgb(${r*0xFF|0}, ${g*0xFF|0}, ${b*0xFF|0}, ${Math.max(0, Math.min(1, a))})` +} \ No newline at end of file diff --git a/dist/color/rgb-to-hsl.js b/dist/color/rgb-to-hsl.js new file mode 100644 index 0000000..eeb2601 --- /dev/null +++ b/dist/color/rgb-to-hsl.js @@ -0,0 +1,12 @@ +/* +Based on https://stackoverflow.com/questions/2348597/why-doesnt-this-javascript-rgb-to-hsl-code-work/54071699#54071699 +posted by Kamil Kiełczewski +input: r,g,b in [0,1], out: h in [0,360) and s,l in [0,1] +*/ +export default function rgbToHsl({r = 0, g = 0, b = 0} = {}) { + const v = Math.max(r,g,b) + const c = v - Math.min(r,g,b) + const f = (1-Math.abs(v+v-c-1)) + const h = c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)) + return {h:60*(h<0?h+6:h), s: f ? c/f : 0, l: (v+v-c)/2} +} \ No newline at end of file diff --git a/dist/color/rgb-to-hsv.js b/dist/color/rgb-to-hsv.js new file mode 100644 index 0000000..68e76d5 --- /dev/null +++ b/dist/color/rgb-to-hsv.js @@ -0,0 +1,11 @@ +/* +Based on https://stackoverflow.com/questions/8022885/rgb-to-hsv-color-in-javascript/54070620#54070620 +posted by Kamil Kiełczewski +input: r,g,b in [0,1], out: h in [0,360) and s,v in [0,1] +*/ +export default function rgbToHsv({r = 0, g = 0, b = 0} = {}) { + const v = Math.max(r,g,b) + const c = v - Math.min(r,g,b) + let h = c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)); + return {h: 60*(h<0?h+6:h), s: v&&c/v, v} + } \ No newline at end of file diff --git a/dist/color/rgba-to-css.js b/dist/color/rgba-to-css.js new file mode 100644 index 0000000..72bdc93 --- /dev/null +++ b/dist/color/rgba-to-css.js @@ -0,0 +1,3 @@ +export default function rgbaToCss({r = 0, g = 0, b = 0, a = 1} = {}) { + return `rgba(${r*0xFF|0}, ${g*0xFF|0}, ${b*0xFF|0}, ${Math.max(0, Math.min(1, a))})` +} \ No newline at end of file diff --git a/dist/component/awsm.css b/dist/component/awsm.css new file mode 100644 index 0000000..84a85f0 --- /dev/null +++ b/dist/component/awsm.css @@ -0,0 +1,20 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex: 1; + flex-direction: column; +} +.views { + display: flex; + overflow: hidden; + flex: 1; +} + +awsm-layout-manager { + flex: 1; +} \ No newline at end of file diff --git a/dist/component/awsm.js b/dist/component/awsm.js new file mode 100644 index 0000000..113ad50 --- /dev/null +++ b/dist/component/awsm.js @@ -0,0 +1,334 @@ +/** + * AWSM - AwesomeWaveSplineMachine MKII. EcmaScript software synthesizer. + * Copyright (C) 2024 C. Nicholas Schreiber + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import Keyboard from './keyboard.js' +import Component from "./component.js" +import SessionManager from '../audio/session-manager.js' +import Session from '../model/session.js' +import LayoutManager from './layout-manager.js' +import KeyboardGroup from './keyboard-group.js' +import Channel from '../model/channel.js' +import Voice from '../model/voice.js' +import DB from '../storage/db.js' +import watch from '../glue/watch.js' +import DatabaseSessionList from './database-session-list.js' +import clone from '../data/clone.js' +import resetState from '../model/reset-state.js' +import SplashScreen from './splash-screen.js' +import SessionEditor from './session-editor.js' +import defaultSession from '../model/default-session.js' + + +const downloadJSON = (filename, data) => { + const blob = new Blob([JSON.stringify(data, null, 2)], { type: "text/json" }) + const link = document.createElement("a") + + link.download = `${filename.toLowerCase().replace(/\s+/g,'_')}.json` + link.href = window.URL.createObjectURL(blob) + link.dataset.downloadurl = ["text/json", link.download, link.href].join(":") + + const evt = new MouseEvent("click", { + view: window, + bubbles: true, + cancelable: true, + }); + + link.dispatchEvent(evt) + link.remove() +} + +export default class AwesomeWaveSplineMachine extends Component { + + static CHANGE = 'change' + static style = 'component/awsm.css' + + #views = document.createElement('div') + #session + #sessionManager = new SessionManager() + + #sessionEditor = LayoutManager.create() + #keyboard = KeyboardGroup.create() + #splashScreen = SplashScreen.create() + + #db = new DB("awsm", 1) + + #saveDelay = 1000 + #saveTriggered = false + #saveReady = true + + constructor() { + super() + console.group("AWSM - AwesomeWaveSplineMachine MKII") + console.log("EcmaScript software synthesizer.") + console.log("Copyright (C) 2024 C. Nicholas Schreiber") + console.log("This program comes with ABSOLUTELY NO WARRANTY") + console.log("This is free software, and you are welcome to redistribute it under certain conditions") + console.groupEnd() + + this.intitialized = false + this.#views.classList.add("views") + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + + async #init() { + + await this.appendStyleLink(AwesomeWaveSplineMachine.style) + this.shadowRoot.append(this.#splashScreen) + + this.#splashScreen.addEventListener(SplashScreen.DISMISS, this.binding(this.#onSplashScreenDismiss)) + + this.shadowRoot.addEventListener("drop", this.binding(this.#onDrop)) + this.shadowRoot.addEventListener("dragover", this.binding(this.#onDragOver)) + + this.intitialized = true + + } + + #onDragOver(ev) { + ev.preventDefault(); + } + + #onDrop(ev) { + const insert = async (file)=>{ + let session = JSON.parse(await file.text()) + session = new Session(clone(session, true)) + session.created = Date.now() + await this.#db.write(session) + } + ev.preventDefault() + if (ev.dataTransfer.items) { + [...ev.dataTransfer.items].forEach(async (item, i) => { + if (item.kind === "file") { + const file = item.getAsFile(); + insert(file) + + } + }); + } else { + [...ev.dataTransfer.files].forEach(async (file, i) => { + insert(file) + }); + } + + } + + #initializeSessioEditor() { + this.#sessionEditor.db = this.#db + + this.#sessionEditor.addEventListener(DatabaseSessionList.TRIGGER_LOAD, this.binding(this.#onTriggerLoad)) + this.#sessionEditor.addEventListener(LayoutManager.NEW_SESSION, this.binding(this.#onNewSession)) + this.#sessionEditor.addEventListener(LayoutManager.DUPLICATE_SESSION, this.binding(this.#onDuplicateSession)) + this.#sessionEditor.addEventListener(LayoutManager.EXPORT_SESSION, this.binding(this.#onExportSession)) + this.#sessionEditor.addEventListener(LayoutManager.DELETE_SESSION, this.binding(this.#onTriggerDelete)) + + this.#sessionEditor.addEventListener(SessionEditor.ZERO, this.binding(this.#onZeroClick)) + } + + + #onZeroClick(e) { + this.#sessionManager.zeroAll(e.detail, false) + } + + #initializeKeyboard() { + + this.#keyboard.classList.add("keyboard-section") + this.#keyboard.addEventListener(Keyboard.KEYDOWN, (e)=>{ + if (this.#session.keyboardFocus) { + const validPath = this.#session.getValidSubpath(this.#session.keyboardFocus) + if (validPath.length >= 2) { + const ref = this.#session.getPathReference(validPath) + if (ref.length) ref.length = 1/e.detail.keydown.frequency + else if (ref.oscillator && ref.oscillator.length) ref.oscillator.length = 1/e.detail.keydown.frequency + } + } + + }) + this.#keyboard.addEventListener(Keyboard.KEYUP, (e)=>{ + }) + this.#keyboard.addEventListener(Keyboard.KEYPRESSURE, (e)=>{ + }) + this.#keyboard.addEventListener(Keyboard.KEYBEND, (e)=>{ + }) + } + + async #initializeDatabase() { + await this.#db.open() + } + + async #initalizeAudioEngine() { + await this.#sessionManager.inititialize() + } + + async #loadRecentOrDefault() { + let session = await this.#db.recent() + + if (session) return new Session(session) + return new Session(defaultSession()) + } + + + async #onSplashScreenDismiss(e) { + await this.#initalizeAudioEngine() + await this.#initializeDatabase() + const session = await this.#loadRecentOrDefault() + + this.#initializeKeyboard() + this.#initializeSessioEditor() + + this.session = session + + this.addToRenderQueue(this.binding(this.#removeSplashScreen)) + } + + #removeSplashScreen() { + this.#splashScreen.remove() + + this.shadowRoot.append(this.#sessionEditor) + this.shadowRoot.append(this.#keyboard) + + } + + async #onTriggerLoad(e) { + const rawSession = await this.#db.read(e.detail) + if (rawSession && (!this.#session || rawSession.id !== this.#session.id)) { + await this.#sessionManager.stopAll() + rawSession.mode = "storage" + this.session = new Session(rawSession) + this.#save() + } + } + + async #onTriggerDelete(e) { + if (!this.#session) return + await this.#sessionManager.stopAll() + const id = this.#session.id + this.session = null + await this.#db.delete(id) + } + + async #onNewSession(e) { + await this.#sessionManager.stopAll() + let session = new Session({mode:"storage"}) + await this.#db.write(session) + this.session = session + } + + async #onDuplicateSession(e) { + if (!this.#session) return + await this.#sessionManager.stopAll() + let session = new Session(clone(this.#session, true)) + session.created = Date.now() + await this.#db.write(session) + this.session = session + } + + async #onExportSession(e) { + if (!this.#session) return + downloadJSON(this.#session.name, this.#session) + } + + #updateKeyboard() { + if (!this.#session || this.#session.mode === "storage") { + this.#keyboard.remove() + } else { + this.shadowRoot.append(this.#keyboard) + } + } + + #onSessionChange(signal) { + if (signal.path[0].property === "tempo") { + this.#session.syncTempo() + } else if (signal.path[0].property === "mode") { + this.#updateKeyboard() + } else if (signal.path[0].property === "state") { + if (signal.path[0].origin instanceof Channel) { + if (signal.path[0].origin.state === Channel.DELETE) { + const channelIndex = this.#session.channels.indexOf(signal.path[0].origin) + this.#session.channels.splice(channelIndex, 1) + this.#session.validateAllPaths() + } + } else if (signal.path[0].origin instanceof Voice) { + if (signal.path[0].origin.state === Voice.TRIGGER_ATTACK) { + signal.path[0].origin.state = Voice.ATTACK + } else if (signal.path[0].origin.state === Voice.TRIGGER_RELEASE) { + signal.path[0].origin.state = Voice.RELEASE + } else if (signal.path[0].origin.state === Voice.DELETE) { + const voice = signal.path[0].origin + const channel = signal.path[1].origin + const voiceIndex = channel.voices.indexOf(voice) + channel.voices.splice(voiceIndex, 1) + this.#session.validateAllPaths() + + } + } + } else if (signal.property === "activeView" || signal.path[0].property === "path") { + + const view = this.#session.views[this.#session.activeView] + if (view && view.path.length>=2) { + const validPath = this.#session.getValidSubpath(view.path) + + const ref = this.#session.getPathReference(validPath) + if (ref.length || ref.oscillator && ref.oscillator.length) { + this.#session.keyboardFocus = validPath + } + } + } + this.#save() + } + + async #save() { + if (!this.#session) return + if (!this.#saveReady) { + this.#saveTriggered = true + return + } + this.#saveTriggered = false + this.#saveReady = false + try { + await this.#db.write(this.#session) + setTimeout(()=>{ + this.#saveReady = true + if (this.#saveTriggered) { + this.#save() + } + }, this.#saveDelay) + } catch(e) { + console.error(e) + } + } + + get session() { + return this.#session + } + + set session(value) { + resetState(value) + this.#session = value + this.#sessionManager.session = this.#session + this.#sessionEditor.session = this.#session + this.#keyboard.session = this.#session + this.#updateKeyboard() + } + + destroy() { + this.#db.close() + super.destroy() + } +} diff --git a/dist/component/button-list.css b/dist/component/button-list.css new file mode 100644 index 0000000..e95fd76 --- /dev/null +++ b/dist/component/button-list.css @@ -0,0 +1,13 @@ +:host { + user-select: none; + display: flex; + white-space: nowrap; + box-sizing: border-box; +} + +.container { + display: flex; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} \ No newline at end of file diff --git a/dist/component/button-list.js b/dist/component/button-list.js new file mode 100644 index 0000000..418ee32 --- /dev/null +++ b/dist/component/button-list.js @@ -0,0 +1,47 @@ + +import updateUIList from "../data/update-ui-list.js" +import Component from "./component.js" +import Button from "./button.js" + + +export default class ButtonList extends Component { + + static style = 'component/button-list.css' + #container = document.createElement('div') + #items + + constructor() { + super() + this.intitialized = false + this.#container.classList.add("container") + this.#init() + } + + async #init() { + await this.appendStyleLink(ButtonList.style) + this.intitialized = true + this.shadowRoot.append(this.#container) + this.addToRenderQueue(this.binding(this.#render)) + } + + set items(value) { + this.#items = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get items() { + return this.#items + } + + #render() { + if (this.#items) { + updateUIList(this.#container, Button, this.#items) + } + } + + destroy() { + updateUIList(this.#container, Button, []) + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/button.css b/dist/component/button.css new file mode 100644 index 0000000..a9f0335 --- /dev/null +++ b/dist/component/button.css @@ -0,0 +1,120 @@ +:host { + user-select: none; + display: flex; + min-width: 90px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; +} + +:host(.wrap) { + flex-basis: 100%; + margin-top:-6px; +} + +:host(.invisible) { + margin-top:-6px; + min-height: 0; + height: 0; +} + +button { + cursor: pointer; + display: flex; + width: 90px; + height: 72px; + border: none; + color:#909090; + background-color: #121212; + align-items: center; + justify-content: space-between; + flex-direction: column; + padding: 6px; + margin: 0; +} + +button.active { + color: rgb(63,63,63); + background-color:rgb(255,255,255); + +} + +button.insert { + color: rgb(0,0,0); + background-color: #446b85; + +} + +button.delete { + color: rgb(0,0,0); + background-color: #c9b02e; + +} + +button.solo { + color: rgb(0,0,0); + background-color: #9e1500; + +} + +button.path { + color:rgb(255,255,255); + background-color: #343435; + +} + +button.logo { + color: rgb(255,255,255); + background-color: #112233; + +} + +button.toggle { + color:#909090; + background: none; +} + +button.toggle .label { + color:rgb(255,255,255); +} + +button.inactive { + color:#909090; + background: none; + cursor: default; +} + + +.label { + display: flex; + font-weight: bold; + font-size: 12px; + flex-wrap: wrap; + overflow-wrap: anywhere; + white-space: normal; +} + +.header { + display: flex; + font-size: 9px; + min-height: 12px; + line-height: 12px; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-start; + overflow: hidden; +} + +.footer { + display: flex; + font-size: 9px; + min-height: 12px; + line-height: 12px; + max-width: 100%; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-end; + overflow: hidden; + text-align: right; +} \ No newline at end of file diff --git a/dist/component/button.js b/dist/component/button.js new file mode 100644 index 0000000..f0bf4f0 --- /dev/null +++ b/dist/component/button.js @@ -0,0 +1,192 @@ +import Component from "./component.js" + +export default class Button extends Component { + + static style = 'component/button.css' + + static UP = 'up' + static DOWN = 'down' + + #label = "" + #header = "" + #footer = "" + #wrap = false + #invisible = false + #action + #id + #path + + #mode = "default" + + #buttonEl = document.createElement("button") + #headerEl = document.createElement("div") + #labelEl = document.createElement("div") + #footerEl = document.createElement("div") + + #isDown + + constructor() { + super() + this.intitialized = false + + this.#headerEl.classList.add("header") + this.#buttonEl.append(this.#headerEl) + + this.#labelEl.classList.add("label") + this.#buttonEl.append(this.#labelEl) + + this.#footerEl.classList.add("footer") + this.#buttonEl.append(this.#footerEl) + + this.#init() + } + + async #init() { + await this.appendStyleLink(Button.style) + this.shadowRoot.append(this.#buttonEl) + this.addToRenderQueue(this.binding(this.#render)) + this.#buttonEl.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#buttonEl.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.#buttonEl.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + Button.DOWN, + { + detail: this, + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#buttonEl.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + Button.UP, + { + detail: this, + bubbles: true, + composed: true + } + ) + ) + } + + set wrap(value) { + this.#wrap = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get wrap() { + return this.#wrap + } + + set invisible(value) { + this.#invisible = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get invisible() { + return this.#invisible + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get label() { + return this.#label + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get header() { + return this.#header + } + + set footer(value) { + this.#footer = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get footer() { + return this.#footer + } + + set mode(value) { + this.#mode = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get mode() { + return this.#mode + } + + set action(value) { + this.#action = value + } + + get action() { + return this.#action + } + + set id(value) { + this.#id = value + } + + get id() { + return this.#id + } + + set path(value) { + this.#path = value + } + + get path() { + return this.#path + } + + #render() { + if (this.#wrap) this.shadowRoot.host.classList.add("wrap") + else this.shadowRoot.host.classList.remove("wrap") + if (this.#invisible) this.shadowRoot.host.classList.add("invisible") + else this.shadowRoot.host.classList.remove("invisible") + this.#labelEl.textContent = this.#label + this.#headerEl.textContent = this.#header + this.#footerEl.textContent = this.#footer + if (this.#mode === "toggle") this.#buttonEl.classList.add("toggle") + else this.#buttonEl.classList.remove("toggle") + if (this.#mode === "active") this.#buttonEl.classList.add("active") + else this.#buttonEl.classList.remove("active") + if (this.#mode === "insert") this.#buttonEl.classList.add("insert") + else this.#buttonEl.classList.remove("insert") + if (this.#mode === "delete") this.#buttonEl.classList.add("delete") + else this.#buttonEl.classList.remove("delete") + if (this.#mode === "path") this.#buttonEl.classList.add("path") + else this.#buttonEl.classList.remove("path") + if (this.#mode === "logo") this.#buttonEl.classList.add("logo") + else this.#buttonEl.classList.remove("logo") + if (this.#mode === "solo") this.#buttonEl.classList.add("solo") + else this.#buttonEl.classList.remove("solo") + if (this.#mode === "inactive") this.#buttonEl.classList.add("inactive") + else this.#buttonEl.classList.remove("inactive") + } + + destroy() { + super.destroy() + } +} \ No newline at end of file diff --git a/dist/component/channel-editor.css b/dist/component/channel-editor.css new file mode 100644 index 0000000..f75fe62 --- /dev/null +++ b/dist/component/channel-editor.css @@ -0,0 +1,14 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} \ No newline at end of file diff --git a/dist/component/channel-editor.js b/dist/component/channel-editor.js new file mode 100644 index 0000000..c78d49d --- /dev/null +++ b/dist/component/channel-editor.js @@ -0,0 +1,152 @@ +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Dynamics from "../model/dynamics.js" +import Component from "./component.js" +import MetricsDisplay from "./metrics-display.js" +import Button from "./button.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import RotaryGroup from "./rotary-group.js" +import VoiceEditor from "./voice-editor.js" + +export default class ChannelEditor extends Component { + + static CHANGE = 'change' + static ZERO = 'zero' + static style = 'component/channel-editor.css' + + #voiceEditor = VoiceEditor.create() + + #zeroButton = Button.create() + #gainRotary = RotaryGroup.create() + #metricsDisplay = MetricsDisplay.create() + #potentialRotary = RotaryGroup.create() + #thresholdRotary = RotaryGroup.create() + #scaleRotary = RotaryGroup.create() + + #channel + + constructor() { + super() + this.intitialized = false + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + this.shadowRoot.append(this.#metricsDisplay) + + + this.#gainRotary.drivers = [ + new GainDriver() + ] + this.shadowRoot.append(this.#gainRotary) + + this.#potentialRotary.drivers = [ + new GainDriver({name:"Potential"}) + ] + this.shadowRoot.append(this.#potentialRotary) + + + this.#thresholdRotary.drivers = [ + new GainDriver({name: "Squeeze Threshold"}) + ] + this.shadowRoot.append(this.#thresholdRotary) + + + this.#scaleRotary.drivers = [ + new GainDriver({name: "Squeeze Scale", max: 4}) + ] + this.shadowRoot.append(this.#scaleRotary) + + + + + + watch(this, "channel", this.binding(this.#onChannelChange)) + this.#init() + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + ChannelEditor.ZERO, + { + composed: true, + detail: this.#channel.id + } + ) + ) + } + + async #init() { + await this.appendStyleLink(ChannelEditor.style) + this.#gainRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGainChange)) + this.#potentialRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onPotentialChange)) + this.#thresholdRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onThresholdChange)) + this.#scaleRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onScaleChange)) + + this.intitialized = true + } + + #onThresholdChange(e) { + this.#channel.dynamics.threshold = this.#thresholdRotary.value + } + + #onPotentialChange(e) { + this.#channel.dynamics.potential = this.#potentialRotary.value + } + + #onScaleChange(e) { + this.#channel.dynamics.scale = this.#scaleRotary.value + } + + + #onGainChange(e) { + this.#channel.gain = this.#gainRotary.value + } + + get channel() { + return this.#channel + } + + set channel(value) { + this.#channel = value + this.#metricsDisplay.audioMetrics = this.#channel.audioMetrics + this.#update() + } + + set settings(value) { + this.#voiceEditor.settings = value + } + + + #onChannelChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + || signal.path.length == 1 + ) this.#update() + + } + + #update() { + if (this.#channel) { + const voice = this.#channel.voices.find(voice => voice.id === this.#channel.activeVoice) + this.#voiceEditor.voice = voice + this.#potentialRotary.value = this.#channel.dynamics.potential + this.#thresholdRotary.value = this.#channel.dynamics.threshold + this.#scaleRotary.value = this.#channel.dynamics.scale + } + + this.#gainRotary.value = this.#channel.gain + + } + + destroy() { + unwatch(this, "channel", this.binding(this.#onChannelChange)) + super.destroy() + + } + +} \ No newline at end of file diff --git a/dist/component/component.js b/dist/component/component.js new file mode 100644 index 0000000..aff2bb1 --- /dev/null +++ b/dist/component/component.js @@ -0,0 +1,117 @@ +import camelToKebab from "../utils/camel-to-kebab.js" + +export default class Component extends HTMLElement { + static prefix = "awsm" + static register = new Set() + + static get componentName() { + return [this.prefix, camelToKebab(this.name)].join('-') + } + + static create(opts) { + const name = this.componentName + if (!this.register.has(name)) { + customElements.define(name, this) + this.register.add(name) + } + const el = document.createElement(name) + if (opts) el.fromObject(opts) + return el + } + + #bindings = new Map() + #renderQueue = new Set() + #animationFrame + #initialized = true + #renderTriggered = false + #resizeObserver + + constructor({resizeObserver = true} = {}) { + super() + if (resizeObserver) { + this.#resizeObserver = new ResizeObserver(this.binding(this.#onResize)) + } + this.attachShadow({ mode: 'open' }) + } + + observe(el) { + this.#resizeObserver.observe(el) + } + + set intitialized(value) { + this.#initialized = value + if (this.#initialized && this.#renderTriggered) this.#triggerRender() + } + + get intitialized() { + return this.#initialized + } + + #onResize(entries) { + for (let entry of entries) { + + if (entry.contentBoxSize?.length > 0) { + this.resize({width: entry.contentBoxSize[0].inlineSize, height: entry.contentBoxSize[0].blockSize}) + break + } + } + } + + resize({width = 0, height = 0}) { + } + + async appendStyleLink(url) { + const styleEl = await new Promise((resolve, reject) => { + const styleEl = document.createElement('link'); + styleEl.type = 'text/css' + styleEl.rel = 'stylesheet' + styleEl.onload = () => resolve(styleEl) + styleEl.onerror = () => reject() + styleEl.href = url + this.shadowRoot.append(styleEl) + }) + return styleEl + } + + binding(fn) { + if (!this.#bindings) return + if (!this.#bindings.has(fn)) { + this.#bindings.set(fn, fn.bind(this)) + } + return this.#bindings.get(fn) + } + + /* Render on animation frame */ + addToRenderQueue(fn) { + if (!this.#renderQueue) return + this.#renderQueue.add(fn) + this.#triggerRender() + } + + /* Force immediate render. */ + render() { + if (this.#animationFrame) cancelAnimationFrame(this.#animationFrame) + this.#render() + } + + destroy() { + this.#bindings = null + this.#renderQueue = null + cancelAnimationFrame(this.#animationFrame) + this.remove() + } + + #triggerRender() { + this.#renderTriggered = false + if (this.#animationFrame) return + if (this.#initialized) this.#animationFrame = requestAnimationFrame(this.binding(this.#render)) + else this.#renderTriggered = true + } + + #render() { + this.#animationFrame = null + for (const fn of this.#renderQueue) fn() + this.#renderQueue = new Set() + } + +} \ No newline at end of file diff --git a/dist/component/database-session-item.css b/dist/component/database-session-item.css new file mode 100644 index 0000000..fbe3396 --- /dev/null +++ b/dist/component/database-session-item.css @@ -0,0 +1,75 @@ +:host { + user-select: none; + display: flex; + width: 186px; + + height: 150px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + gap: 6px; + justify-content: space-between; + background-color: #121212; + color: #909090; + cursor: pointer; +} +:host(.active){ + background-color: #FFFFFF; + color: #000000; +} +canvas { + width: 186px; + height: 72px; + image-rendering: crisp-edges; +} +.container { + width: 186px; + padding: 6px; + height: 72px; + display: flex; + gap: 2px; + box-sizing: border-box; + flex-direction: column; +} +.name { + display: flex; + font-family: sans-serif; + font-weight: bold; + font-size: 12px; + flex-wrap: wrap; + align-content: center; + word-wrap: break-word; + white-space: normal; + +} + +.id { + display: flex; + font-family: sans-serif; + font-size: 9px; + word-wrap: unset; + text-overflow: ellipsis; + white-space: normal; + white-space: nowrap; + +} +.date { + display: flex; + font-family: sans-serif; + font-size: 9px; + flex-wrap: wrap; + word-wrap: break-word; + white-space: normal; + flex: 1; +} + +.channels { + display: flex; + font-family: sans-serif; + font-size: 9px; + flex-wrap: wrap; + word-wrap: break-word; + white-space: normal; + +} \ No newline at end of file diff --git a/dist/component/database-session-item.js b/dist/component/database-session-item.js new file mode 100644 index 0000000..348e2aa --- /dev/null +++ b/dist/component/database-session-item.js @@ -0,0 +1,244 @@ + +import Component from "./component.js" +export default class DatabaseSessionItem extends Component { + + static style = 'component/database-session-item.css' + static UP = 'up' + static DOWN = 'down' + #tree + #name = "" + #id = "" + #changed = "" + #active = false + #isDown + #canvas = document.createElement("canvas") + #ctx + #container = document.createElement("div") + #nameElement = document.createElement("div") + #idElement = document.createElement("div") + #dateElement = document.createElement("div") + #channelsElement = document.createElement("div") + #voicesElement = document.createElement("div") + + constructor() { + super() + this.intitialized = false + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 180) + this.#canvas.setAttribute("height", 72) + + + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + + this.#container.classList.add("container") + this.shadowRoot.append(this.#container) + + this.#nameElement.classList.add("name") + this.#container.append(this.#nameElement) + + this.#idElement.classList.add("id") + this.#container.append(this.#idElement) + + this.#dateElement.classList.add("date") + this.#container.append(this.#dateElement) + + this.#channelsElement.classList.add("channels") + this.#container.append(this.#channelsElement) + + //this.#voicesElement.classList.add("channels") + //this.#container.append(this.#voicesElement) + + this.#init() + } + async #init() { + await this.appendStyleLink(DatabaseSessionItem.style) + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + DatabaseSessionItem.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + DatabaseSessionItem.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + set active(value) { + this.#active = value + this.addToRenderQueue(this.binding(this.#render)) + this.addToRenderQueue(this.binding(this.#renderTree)) + } + + get active() { + return this.#active + } + + set id(value) { + this.#id = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get id() { + return this.#id + } + + + set name(value) { + this.#name = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get name() { + return this.#name + } + + + set changed(value) { + this.#changed = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get changed() { + return this.#changed + } + + set tree(value) { + if (JSON.stringify(this.#tree) === JSON.stringify(value)) return + this.#tree = value + this.addToRenderQueue(this.binding(this.#renderTree)) + } + + get tree() { + return this.#tree + } + + #render() { + if (this.#active) this.classList.add("active") + else this.classList.remove("active") + this.#nameElement.textContent = this.#name + this.#idElement.textContent = this.#id + this.#dateElement.textContent = new Date(this.#changed).toISOString().replace('T', ' ').slice(0, -5) + + let voices = 0 + this.#tree.branches.forEach(channel => {voices += channel.branches.length}) + this.#channelsElement.textContent = `${this.#tree.branches.length} Channels, ${voices} Voices` + //this.#voicesElement.textContent = `${voices} Voices` + } + + #lineWidth = 4 + #branchDepth = 0 + #branchSpan = 0 + #padding = 6 + + + + #renderRecursive(x, y, branch, lineWidth=2) { + let sx = x-(branch.span * this.#branchSpan)/2 + this.#ctx.save() + const col = (this.#active)?"#000000":"#909090" + this.#ctx.strokeStyle = col + this.#ctx.lineWidth = lineWidth + this.#ctx.lineCap = "square" + for (let i = 0; i { + session.active = (this.#session && session.id === this.#session.id) + }) + updateUIList(this.#container, DatabaseSessionItem, sessions) + } + + destroy() { + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/display.css b/dist/component/display.css new file mode 100644 index 0000000..ce43f98 --- /dev/null +++ b/dist/component/display.css @@ -0,0 +1,87 @@ +:host { + user-select: none; + display: flex; + min-width: 90px; + min-height: 72px; + width: 90px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + padding: 6px; +} + +.container { + display:flex; + flex-direction: column; + flex: 1; + justify-content: space-between; +} + +.header, .footer{ + font-family: sans-serif; + color:rgb(128,128,128); + font-size: 9px; + height: 12px; + line-height: 12px; + align-self: flex-start; +} + +:host(.clickable) { + cursor: pointer; +} + +.footer { + display: flex; + font-size: 9px; + min-height: 12px; + line-height: 12px; + max-width: 100%; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-end; + overflow: hidden; + text-align: right; +} + +.mode { + display: flex; + flex-direction: row; + font-size: 12px; + margin-top: -2px; + height: 12px; + color:rgb(127,127,127); + gap: 3px; +} + +.value-container { + display:flex; + flex-direction: row; + align-items: baseline; + gap: 3px; + height: 28px; + max-width: 78px; + justify-content: center; +} + +.value { + display:flex; + font-family: sans-serif; + font-size: 24px; + color: rgba(255, 255, 255, 1); +} + +.unit { + display:flex; + font-family: sans-serif; + font-size: 11px; + color:rgba(255, 255, 255, 1); + vertical-align: baseline; +} + +.precision { + display:flex; + font-family: sans-serif; + font-size: 11px; + color:rgba(255, 255, 255, 1); + vertical-align: baseline; +} \ No newline at end of file diff --git a/dist/component/display.js b/dist/component/display.js new file mode 100644 index 0000000..6b7777a --- /dev/null +++ b/dist/component/display.js @@ -0,0 +1,180 @@ +import Component from "./component.js" + +export default class Display extends Component { + + static UP = 'up' + static DOWN = 'down' + static CHANGE = 'change' + static style = 'component/display.css' + + #precisionEl = document.createElement('div') + #valueEl = document.createElement('div') + #headerEl = document.createElement('div') + #footerEl = document.createElement('div') + #modeEl = document.createElement('div') + #unitEl = document.createElement('div') + #containerEl = document.createElement('div') + #valueContainerEl = document.createElement('div') + + #precision = "" + #value = "0" + #label = "" + #unit = "Hz" + #footer = "" + + #modes = [] + #mode + + #isDown + #clickable = false + + constructor() { + super() + this.intitialized = false + this.#containerEl.classList.add("container") + this.#headerEl.classList.add("header") + this.#footerEl.classList.add("footer") + this.#modeEl.classList.add("mode") + this.#valueContainerEl.classList.add("value-container") + this.#precisionEl.classList.add("precision") + this.#valueEl.classList.add("value") + this.#unitEl.classList.add("unit") + this.#containerEl.appendChild(this.#headerEl) + this.#valueContainerEl.appendChild(this.#precisionEl) + this.#valueContainerEl.appendChild(this.#valueEl) + this.#valueContainerEl.appendChild(this.#unitEl) + this.#containerEl.appendChild(this.#valueContainerEl) + this.#containerEl.appendChild(this.#footerEl) + this.shadowRoot.append(this.#containerEl) + + this.#containerEl.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#containerEl.addEventListener("pointerup", this.binding(this.#onPointerUp)) + + this.#init() + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.#containerEl.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + Display.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#containerEl.releasePointerCapture(e.pointerId) + this.#isDown = null + this.dispatchEvent( + new CustomEvent( + Display.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + async #init() { + await this.appendStyleLink(Display.style) + this.intitialized = true + this.addToRenderQueue(this.binding(this.#render)) + } + + + set value(value) { + this.#value = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get value() { + return this.#value + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get label() { + return this.#label + } + + set unit(value) { + this.#unit = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get unit() { + return this.#unit + } + + set precision(value) { + this.#precision = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get precision() { + return this.#precision + } + + set footer(value) { + this.#footer = value + } + + get footer() { + return this.#footer + } + + set modes(value) { + this.#modes = value + } + + get modes() { + return this.#modes + } + + set mode(value) { + this.#mode = value + } + + get mode() { + return this.#mode + } + + set clickable(value) { + this.#clickable = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get clickable() { + return this.#clickable + } + + + #render() { + this.#headerEl.textContent = this.#label + this.#precisionEl.textContent = this.#precision + this.#valueEl.textContent = this.#value + this.#unitEl.textContent = this.#unit + this.#footerEl.textContent = this.#footer + if (this.#clickable && !this.shadowRoot.host.classList.contains("clickable")) this.shadowRoot.host.classList.add("clickable") + else if (!this.#clickable && this.shadowRoot.host.classList.contains("clickable")) this.shadowRoot.host.classList.remove("clickable") + + } + + destroy() { + + this.#containerEl.remove() + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/fm-editor.css b/dist/component/fm-editor.css new file mode 100644 index 0000000..5e66d4b --- /dev/null +++ b/dist/component/fm-editor.css @@ -0,0 +1,22 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: column; + gap: 6px; +} + +.container { + flex-direction: column; + max-width: 100%; +} + +canvas { + display:flex; +} \ No newline at end of file diff --git a/dist/component/fm-editor.js b/dist/component/fm-editor.js new file mode 100644 index 0000000..630789d --- /dev/null +++ b/dist/component/fm-editor.js @@ -0,0 +1,63 @@ +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Component from "./component.js" +import RangeDriver from "./rotary-driver/range-driver.js" +import RotaryGroup from "./rotary-group.js" + +export default class FMEditor extends Component { + + static CHANGE = 'change' + static style = 'component/fm-editor.css' + + + #fmRangeRotary = RotaryGroup.create() + #waveSplineOscillator + + + constructor() { + super() + this.intitialized = false + this.#fmRangeRotary.drivers = [ + new RangeDriver() + ] + this.shadowRoot.append(this.#fmRangeRotary) + + this.#fmRangeRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onFMRangeChange)) + + watch(this, "waveSplineOscillator", this.binding(this.#onWaveSplineOscillatorChange)) + this.#init() + } + + #onFMRangeChange(e) { + this.#waveSplineOscillator.fmRange = this.#fmRangeRotary.value + } + + async #init() { + await this.appendStyleLink(FMEditor.style) + this.intitialized = true + } + + get waveSplineOscillator() { + return this.#waveSplineOscillator + } + + set waveSplineOscillator(value) { + this.#waveSplineOscillator = value + this.#update() + } + + #onWaveSplineOscillatorChange(signal) { + if (signal.path[0].property === "phase" || signal.path.length > 1) return + this.#update() + } + + #update() { + this.#fmRangeRotary.value = this.#waveSplineOscillator.fmRange + } + + destroy() { + unwatch(this, "waveSplineOscillator", this.binding(this.#onWaveSplineOscillatorChange)) + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/keyboard-group.css b/dist/component/keyboard-group.css new file mode 100644 index 0000000..0340c9c --- /dev/null +++ b/dist/component/keyboard-group.css @@ -0,0 +1,33 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; +} +.settings { + display: flex; + flex-direction: row; + flex-wrap: wrap; + margin: 6px; +} +.status { + height: 18px; + padding: 6px; + font-size: 9px; + line-height: 12px; + color: #909090; + font-family: sans-serif; +} +awsm-keyboard { + + width: 100%; + height: 72px; +} +.row { + display: flex; + flex-direction: row; +} \ No newline at end of file diff --git a/dist/component/keyboard-group.js b/dist/component/keyboard-group.js new file mode 100644 index 0000000..c708c23 --- /dev/null +++ b/dist/component/keyboard-group.js @@ -0,0 +1,107 @@ +import watch from "../glue/watch.js" +import KeyboardSettings from "../model/keyboard-settings.js" +import Component from "./component.js" +import Keyboard from "./keyboard.js" + +export default class KeyboardGroup extends Component { + + static CHANGE = 'change' + static style = 'component/keyboard-group.css' + #keyboard = Keyboard.create() + #statusEl = document.createElement('div') + #session + + constructor() { + super() + this.intitialized = false + this.#statusEl.classList.add("status") + this.shadowRoot.append(this.#statusEl) + this.shadowRoot.append(this.#keyboard) + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(KeyboardGroup.style) + this.intitialized = true + this.#update() + } + + #onSessionChange(signal) { + if ( + signal.property === "activeView" + || signal.path[0].property === "path" + || signal.path[0].property === "length" + || signal.path[0].origin instanceof KeyboardSettings + || signal.path[0].property === "keyboardFocus" + ) this.#update() + } + + set session(value) { + this.#session = value + this.#update() + } + + get session() { + return this.#session + } + + + #getOscillatorName(oscillator) { + switch (oscillator) { + case "am": + return "AM" + case "fm": + return "FM" + case "transpose": + return "Pitch" + case "em": + return "Exponent" + case "sx": + return "Scale" + case "gain": + default: + return "Gain" + } + } + + #update() { + if (!this.#session) return + this.#keyboard.start = this.#session.keyboardSettings.start + this.#keyboard.keys = this.#session.keyboardSettings.keys + this.#keyboard.subdivisions = this.#session.keyboardSettings.subdivisions + + const validPath = this.#session.getValidSubpath(this.#session.keyboardFocus) + + const status = [] + if ( validPath.length>=2) { + const ref = this.#session.getPathReference(validPath) + if (ref.length) this.#keyboard.frequency = 1/ref.length + else if (ref.oscillator && ref.oscillator.length) this.#keyboard.frequency = 1/ref.oscillator.length + else this.#keyboard.frequency = 0 + const path = [] + status.push(this.#session.name) + let pref = this.#session + for(let i = 0; i 0) { + + const closest = new Note(findClosestNote(this.#frequency)) + if (Math.abs(closest.match - this.#frequency) < .001) { + highlight = closest.index + } + } + + for (let i=0; i{console.log(x.view.id, e.target.id);return x.view.id === e.target.id}) + console.log(node) + node.scrollIntoView() + } else if (e.target.action === "add-view") { + this.#session.views.push({}) + this.#session.activeView = this.#session.views.length - 1 + } else if (e.target.action === "delete-view") { + this.#session.views.splice(this.#session.activeView, 1) + this.#session.activeView = Math.min(this.#session.views.length - 1, this.#session.activeView) + } else if ( e.target.action === "show-storage") { + this.#session.mode = "storage" + } else if ( e.target.action === "show-view") { + if (this.#session) { + this.#session.mode = "view" + } + } else if ( e.target.action === "new-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.NEW_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } else if ( e.target.action === "delete-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.DELETE_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } else if ( e.target.action === "duplicate-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.DUPLICATE_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } else if ( e.target.action === "export-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.EXPORT_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } + } + + #onContainerUp(e) { + let target = Array.from(this.#container.children).indexOf(e.target) + if (target<0) return + this.#session.activeView = target + + } + + set session(value) { + this.#session = value + this.#storageEditor.session = this.#session + } + + get session() { + return this.#session + } + + set db(value) { + this.#storageEditor.db = value + } + + get db() { + return this.#storageEditor.db + } + + #onSessionChange(signal) { + if (signal.path.length > 1) return + this.#update() + } + + #update() { + let list = [] + if (!this.#session) { + list.push(/*{ + header: "", + footer: "", + label: "AWSM", + mode: "logo", + invisible: false, + wrap: false + },*/{ + header: "AWSM", + footer: "",// "none", + label: "Database", + mode: "toggle", + action: "show-view", + invisible: false, + wrap: false + },{ + header: "Session", + footer: "", + label: "New", + mode: "insert", + action: "new-session", + invisible: false, + wrap: false + }) + } else if (this.#session.mode === "storage") { + list.push(/*{ + header: "", + footer: "", + label: "AWSM", + mode: "logo", + invisible: false, + wrap: false + },*/{ + header: "AWSM", + footer: "",// this.#session.name, + label: "Database", + mode: "logo", + action: "show-view", + invisible: false, + wrap: false + },{ + header: "Session", + footer: this.#session.name, + label: "Duplicate", + mode: "insert", + action: "duplicate-session", + invisible: false, + wrap: false + },{ + header: "Session", + footer: this.#session.name, + label: "Export", + mode: "insert", + action: "export-session", + invisible: false, + wrap: false + },{ + header: "Session", + footer: "", + label: "New", + mode: "insert", + action: "new-session", + invisible: false, + wrap: false + },{ + header: "Session", + footer: this.#session.name, + label: "Delete", + mode: "delete", + action: "delete-session", + invisible: false, + wrap: false + }) + } else if (this.#session.mode === "view") { + + + const views = this.#session.views.map((view, index) => {return { + session: this.#session, + view, + active: this.#session.activeView == index + }}) + updateUIList(this.#container, ViewEditor, views) + + list = this.#session.views.map( + (view, index) => { + return { + header: "View", + label: view.name, + footer: "", + mode: (this.#session.activeView == index) ? "active":"default", + action: "select-view", + id: index, + invisible: false, + wrap: false + } + } + ) + + list.unshift(/*{ + header: "", + footer: "", + label: "AWSM", + mode: "logo", + invisible: false, + wrap: false + },*/{ + header: "AWSM", + footer: "",//this.#session.name, + label: "Perform", + mode: "logo", + action: "show-storage", + invisible: false, + wrap: false + }) + list.push({ + header: "View", + label: "Add", + footer: "", + mode: "insert", + action: "add-view", + invisible: false, + wrap: false + }) + if (this.#session.activeView >= 0 && this.#session.activeView < this.#session.views.length) { + list.push({ + header: "View", + label: "Delete", + footer: this.#session.views[this.#session.activeView].name, + mode: "delete", + action: "delete-view", + invisible: false, + wrap: false + }) + } + } + + updateUIList(this.#navigationContent, Button, list) + this.addToRenderQueue(this.binding(this.#updateDom)) + + } + + #updateDom() { + + if (!this.#session || this.#session.mode === "storage") { + if (!this.#storageEditor.parentNode) this.shadowRoot.append(this.#storageEditor) + if (this.#container.parentNode) this.#container.remove() + } else { + if (!this.#container.parentNode) this.shadowRoot.append(this.#container) + if (this.#storageEditor.parentNode) this.#storageEditor.remove() + + } + } + + destroy() { + unwatch(this, "session", this.binding(this.#onSessionChange)) + super.destroy() + } +} \ No newline at end of file diff --git a/dist/component/metrics-display.css b/dist/component/metrics-display.css new file mode 100644 index 0000000..e7b4113 --- /dev/null +++ b/dist/component/metrics-display.css @@ -0,0 +1,40 @@ +:host { + user-select: none; + display: flex; + width: 90px; + height: 72px; + white-space: nowrap; + box-sizing: border-box; + touch-action: none; + flex-direction: column; + flex:0; + padding: 6px; + cursor: pointer; +} + +canvas { + touch-action: none; + display:flex; + height: 36px; + width: 78px; +} + +.header, .footer{ + font-family: sans-serif; + color:rgb(128,128,128); + font-size: 9px; + height: 12px; + align-self: flex-start; +} + +.footer { + display: flex; + min-height: 12px; + line-height: 12px; + max-width: 100%; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-end; + overflow: hidden; + text-align: right; +} \ No newline at end of file diff --git a/dist/component/metrics-display.js b/dist/component/metrics-display.js new file mode 100644 index 0000000..3e87d11 --- /dev/null +++ b/dist/component/metrics-display.js @@ -0,0 +1,152 @@ +import unwatch from "../glue/unwatch.js" +import Component from "./component.js" + +export default class MetricsDisplay extends Component { + + static CHANGE = 'change' + static style = 'component/metrics-display.css' + + #canvas = document.createElement('canvas') + #ctx + + #padding = 4 + #lineWidth = 2 + + #innerWidth + #innerHeight + #top + #left + + #audioMetrics + + #header = "" + #headerEl = document.createElement("div") + #footerEl = document.createElement("div") + #freeze = false + + constructor() { + super() + this.intitialized = false + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 60) + this.#canvas.setAttribute("height", 36) + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + + this.#footerEl.classList.add("footer") + this.shadowRoot.append(this.#footerEl) + + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + + this.#init() + } + + #onPointerUp(e) { + this.freeze = !this.freeze + } + + async #init() { + await this.appendStyleLink(MetricsDisplay.style) + this.#calculate() + this.#renderLabels() + this.#renderLoop() + this.intitialized = true + } + + resize(contentRect) { + super.resize(contentRect) + this.#calculate() + } + + set audioMetrics(value) { + this.#audioMetrics = value + } + + get audioMetrics() { + return this.#audioMetrics + } + + get header() { + return this.#header + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get header() { + return this.#header + } + + set freeze(value) { + this.#freeze = value + this.addToRenderQueue(this.binding(this.#renderLabels)) + } + + get freeze() { + return this.#freeze + } + + #calculate() { + this.#innerWidth = this.#canvas.width - this.#padding * 2 + this.#innerHeight = this.#canvas.height - this.#padding * 2 + this.#top = this.#padding + this.#left = this.#padding + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #renderLoop() { + requestAnimationFrame(()=>{ + this.#renderCanvas() + this.#renderLoop() + }) + } + + #renderCanvas() { + + if (this.#freeze) return + this.#headerEl.textContent = this.#header || "Oscilloscope" + this.#ctx.clearRect(0, 0, this.#canvas.width, this.#canvas.height) + if (!this.#audioMetrics) return + this.#audioMetrics.callback() + let frame = this.#audioMetrics.frame + let hFactor = this.#innerWidth/frame.length + let vFactor = this.#innerHeight/0xFF + this.#ctx.save() + this.#ctx.beginPath() + this.#ctx.lineJoin = "round" + this.#ctx.strokeStyle = "#FFFFFF" + this.#ctx.lineWidth = this.#lineWidth + for (let i = 0; i < frame.length; i++) { + const val = frame[i] + const x = this.#left + i * hFactor + const y = this.#top + (0xFF-val) * vFactor + if (x==0) { + this.#ctx.moveTo(x,y) + } else { + this.#ctx.lineTo(x,y) + } + } + this.#ctx.stroke() + this.#ctx.restore() + } + + #renderLabels() { + if (this.#freeze) { + this.#footerEl.textContent = "paused" + } else { + this.#footerEl.textContent = "" + } + } + + destroy() { + unwatch(this) + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/multi-pole-fader.css b/dist/component/multi-pole-fader.css new file mode 100644 index 0000000..52df7e9 --- /dev/null +++ b/dist/component/multi-pole-fader.css @@ -0,0 +1,17 @@ +:host { + user-select: none; + display: flex; + min-width: 90px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex:0; + padding: 6px; + cursor: pointer; +} +canvas { + display:flex; + width: 78px; + height: 60px; +} \ No newline at end of file diff --git a/dist/component/multi-pole-fader.js b/dist/component/multi-pole-fader.js new file mode 100644 index 0000000..06da6cf --- /dev/null +++ b/dist/component/multi-pole-fader.js @@ -0,0 +1,292 @@ +import hslToRgb from "../color/hsl-to-rgb.js" +import rgbaToCss from "../color/rgba-to-css.js" +import calculateAngle from "../math/calculate-angle.js" +import { TAU } from "../math/contants.js" +import calculateLength from "../math/calculate-length.js" +import Point from "../model/point.js" +import Component from "./component.js" +import calculateCirclePoint from "../math/calculate-circle-point.js" +import translatePoint from "../math/translate-point.js" +import interpolatePoint from "../math/interpolate-point.js" +import Signal from "../glue/signal.js" +import calculatePoleValue from "../math/calculate-pole-value.js" + + +export default class MultiPoleFader extends Component { + + static CHANGE = 'change' + static style = 'component/multi-pole-fader.css' + + #canvas = document.createElement('canvas') + #ctx + #poles = 6 + #position = new Point({x:0, y:0}) + + #angleOffset = -Math.PI/2 + #padding = 16 + #radius + #diameter + #segmentAngle + #perimeterSegments + #perimeterSegmentAngle + #magnitude + + + #perimeterColor = hslToRgb({h: 0, s: 0, l: 1}) + #handleColor = hslToRgb({h: 0, s: 0, l: 1}) + #lineWidth = 2 + #handleRadius = 4 + + + #brightness = 1 + + #isDown + + constructor() { + super() + this.intitialized = false + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 78) + this.#canvas.setAttribute("height", 60) + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + this.#init() + } + + async #init() { + await this.appendStyleLink(MultiPoleFader.style) + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointermove", this.binding(this.#onPointerMove)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.addEventListener("lostpointercapture", this.binding(this.#onPointerLost)) + this.addEventListener("pointercancel", this.binding(this.#onPointerCancel)) + Signal.subscribe(this.#position, this.binding(this.#onPositionChange)) + this.#calculate() + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.#positionFromEvent(e) + } + + #onPointerCancel(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerLost(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerMove(e) { + if (this.#isDown !== e.pointerId) return + this.#positionFromEvent(e) + } + + #positionFromEvent(e) { + let rect = this.#canvas.getBoundingClientRect(); + let x = e.clientX - rect.left + let y = e.clientY - rect.top + + // proportional + let p = { + x: ((x - this.#canvas.width / 2) / this.radius), + y: ((y - this.#canvas.height / 2) / this.radius) + } + + const distance = calculateLength(p.x, p.y) + if (distance > 1) { + // limit to perimeter + const angle = calculateAngle(p) + this.#position.x = Math.cos(angle); + this.#position.y = Math.sin(angle); + } else { + this.#position.x = p.x + this.#position.y = p.y + } + this.dispatchEvent( + new CustomEvent( + MultiPoleFader.CHANGE, + { + composed: true + } + ) + ) + } + + get position() { + return this.#position + } + + #onPositionChange() { + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + set brightness(value) { + this.#brightness = Math.max(1, value) + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get brightness() { + return this.#brightness + } + + set angleOffset(value) { + this.#angleOffset = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get angleOffset() { + return this.#angleOffset + } + + set poles(value) { + if (this.#poles == value) return + this.#poles = value + this.#calculate() + } + + get poles() { + return this.#poles + } + + get radius() { + return this.#radius + } + + get diameter() { + return this.#diameter + } + + get segmentAngle() { + return this.#segmentAngle + } + + get perimeterSegments() { + return this.#perimeterSegments + } + + get perimeterSegmentAngle() { + return this.#perimeterSegmentAngle + } + + get magnitude() { + return this.#magnitude + } + + #calculate() { + this.#diameter = Math.min( + this.#canvas.width - this.#padding * 2, + this.#canvas.height - this.#padding * 2 + ) + this.#radius = this.#diameter / 2 + if (this.poles > 0) { + this.#segmentAngle = TAU / this.#poles + if (!(this.#poles % 2)) { + this.#perimeterSegments = this.#poles + this.#perimeterSegmentAngle = this.#segmentAngle + } else { + this.#perimeterSegments = this.#poles * 2 + this.#perimeterSegmentAngle = this.#segmentAngle / 2 + } + this.#magnitude = Math.max(1, this.#poles / 2) + } + + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + calculatePoleValue(pole) { + return calculatePoleValue(pole, this.#poles, this.#position) + } + + #renderCanvas() { + let w = this.#canvas.width + let h = this.#canvas.height + let cx = w/2 + let cy = h/2 + let c = {x: w/2, y: h/2} + + this.#ctx.clearRect(0, 0, this.#canvas.width, this.#canvas.height) + this.#ctx.save() + + // circle + this.#ctx.beginPath(); + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.strokeStyle = rgbaToCss(this.#perimeterColor) + this.#ctx.arc(c.x, c.y, this.radius, 0, 2 * Math.PI); + this.#ctx.stroke(); + + if (this.#poles > 0) { + // axis + for (let i = 0; i < this.poles; i++) { + const angle = this.angleOffset + i * this.segmentAngle + let s = translatePoint(calculateCirclePoint(this.radius, angle), c) + let e = translatePoint(calculateCirclePoint(this.radius, angle + Math.PI), c) + this.#ctx.save() + this.#ctx.beginPath(); + let col = i*128/this.poles + this.#ctx.lineWidth = this.#lineWidth / 2 + this.#ctx.strokeStyle = "#808080" + this.#ctx.moveTo (s.x, s.y); + this.#ctx.lineTo (e.x, e.y); + this.#ctx.stroke(); + this.#ctx.restore() + } + + // poles + for (let i = 0; i < this.poles; i++) { + const angle = this.angleOffset + i * this.segmentAngle + let s = translatePoint(calculateCirclePoint(this.radius, angle), c) + let e = translatePoint(calculateCirclePoint(this.radius, angle + Math.PI), c) + let q = this.calculatePoleValue(i) + let t = interpolatePoint(s, e, q) + this.#ctx.save() + this.#ctx.beginPath() + this.#ctx.fillStyle = "#909090" + this.#ctx.arc(t.x, t.y, this.#handleRadius / 2, 0, 2 * Math.PI) + this.#ctx.fill() + this.#ctx.restore() + + this.#ctx.save() + this.#ctx.fillStyle = "#909090" + let tp = translatePoint(calculateCirclePoint(this.radius + 10, angle + Math.PI), c) + this.#ctx.font = "9px sans-serif" + this.#ctx.textBaseline = "middle" + this.#ctx.textAlign = "center" + this.#ctx.fillText(i+1, tp.x, tp.y) + this.#ctx.restore() + + + } + + // handle + this.#ctx.save() + this.#ctx.beginPath(); + this.#ctx.fillStyle = rgbaToCss(this.#handleColor) + this.#ctx.arc(cx + this.#position.x * this.radius, cy + this.#position.y * this.radius, this.#handleRadius, 0, 2 * Math.PI); + this.#ctx.fill() + this.#ctx.restore() + } + } + + destroy() { + Signal.unsubscribe(this.#position, this.binding(this.#onPositionChange)) + this.#canvas.removeEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + this.#canvas.removeEventListener("pointerup", this.binding(this.#onPointerUp)) + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/oscillator-editor.css b/dist/component/oscillator-editor.css new file mode 100644 index 0000000..c1cc690 --- /dev/null +++ b/dist/component/oscillator-editor.css @@ -0,0 +1,35 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + gap: 3px; +} + +.navigation { + display:flex; + flex: 1; + flex-direction: row; +} + +.row { + display:flex; + flex: 1; + flex-direction: row; +} +.toolbar { + display: flex; + flex-direction: row; +} + +awsm-wave-spline-graph { + flex: 1; +} + +canvas { + display:flex; +} \ No newline at end of file diff --git a/dist/component/oscillator-editor.js b/dist/component/oscillator-editor.js new file mode 100644 index 0000000..b4bd50c --- /dev/null +++ b/dist/component/oscillator-editor.js @@ -0,0 +1,149 @@ +import watch from "../glue/watch.js" +import beautifyTime from "../music/beautify-time.js" +import Component from "./component.js" +import FMEditor from "./fm-editor.js" +import Button from "./button.js" +import WaveSplineEditor from "./wave-spline-editor.js" + +export default class OscillatorEditor extends Component { + + static ZERO = 'zero' + static style = 'component/oscillator-editor.css' + #last + #parent + #reference + #settings + #zeroButton = Button.create() + #waveSplineContainer = document.createElement('div') + #waveSplineEditor = WaveSplineEditor.create() + #fmEditor = FMEditor.create() + + constructor() { + super() + this.intitialized = false + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + this.#waveSplineContainer.append(this.#waveSplineEditor) + this.shadowRoot.append(this.#waveSplineContainer) + + watch(this, "reference", this.binding(this.#onReferenceChange)) + watch(this, "settings", this.binding(this.#onSettingsChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(OscillatorEditor.style) + this.intitialized = true + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + OscillatorEditor.ZERO, + { + composed: true, + detail: this.#reference.id + } + ) + ) + } + + set last(value) { + this.#last = value + this.#update() + } + + get last() { + return this.#last + } + + set parent(value) { + this.#parent = value + this.#update() + } + + get parent() { + return this.#parent + } + + set reference(value) { + this.#reference = value + } + + get reference() { + return this.#reference + } + + set settings(value) { + this.#settings = value + } + + get settings() { + return this.#settings + } + + #onReferenceChange(signal) { + if (signal.path.length && signal.path[0].property === "phase") return + if (signal.path.length == 1 || signal.path[0].property == "viewZoom") this.#update() + } + + #onSettingsChange(signal) { + if (signal.path.length == 1) this.#update() + } + + #update() { + if (!this.#reference || !this.#parent) return + let last = this.#last // validPath.slice(-1)[0] + let parent = this.#parent // this.#session.getPathReference(validPath.slice(0,-1)) + const ref = this.#reference // this.#session.getPathReference(validPath) + + if (last === "fm") this.#fmEditor.waveSplineOscillator = parent + if (last === "fm") { + if (!this.#fmEditor.parentElement) { + // add fm control + this.#waveSplineContainer.insertBefore(this.#fmEditor, this.#waveSplineEditor) + } + } else { + if (this.#fmEditor.parentElement) { + this.#fmEditor.remove() + } + } + + if (last === "fm") { + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "transpose") { + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "am") { + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "em") { + this.#waveSplineEditor.zero = 0 + this.#waveSplineEditor.minYLabel = 0 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "sx") { + this.#waveSplineEditor.zero = 0 + this.#waveSplineEditor.minYLabel = 0 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "gain") { + this.#waveSplineEditor.zero = 0 + this.#waveSplineEditor.minYLabel = 0 + this.#waveSplineEditor.maxYLabel = 1 + + } + const time = beautifyTime(ref.length * ref.wave.viewZoom) + this.#waveSplineEditor.maxXLabel = `${time.value} ${time.unit}` + this.#waveSplineEditor.waveSplineOscillator = ref + this.#waveSplineEditor.settings = this.#settings + } + +} \ No newline at end of file diff --git a/dist/component/rotary-driver/bar-driver.js b/dist/component/rotary-driver/bar-driver.js new file mode 100644 index 0000000..17dc576 --- /dev/null +++ b/dist/component/rotary-driver/bar-driver.js @@ -0,0 +1,44 @@ +import RotaryDriver from "./rotary-driver.js" + +export default class BarDriver extends RotaryDriver { + tempo = 120 / 60 / 4 + constructor(opts) { + super() + this.name = "Bars" + this.id = "bar" + this.min = 1 + this.max = 24 + this.step = 1 + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return this.max + } + + get minLabel() { + return this.min + } + + toLocal(value) { + return value * this.tempo + } + + fromLocal(value) { + return value / this.tempo + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/beat-driver.js b/dist/component/rotary-driver/beat-driver.js new file mode 100644 index 0000000..4e52b72 --- /dev/null +++ b/dist/component/rotary-driver/beat-driver.js @@ -0,0 +1,38 @@ +import beautifyTime from "../../music/beautify-time.js" +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" +import TimeDriver from "./time-driver.js" + +export default class BeatDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Beat length" + this.id = "beat" + this.min = 0.25 + this.step = 0.01 + this.max = 2 + this.center = this.min + Object.assign(this, opts) + } + + toLocal(value) { + return 1/value/4 + } + + fromLocal(value) { + return 1/(value*4) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + const unitObject = beautifyTime(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded,.1), + unit: unitObject.unit, + valueString: unitObject.value + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/bpm-driver.js b/dist/component/rotary-driver/bpm-driver.js new file mode 100644 index 0000000..0dc34df --- /dev/null +++ b/dist/component/rotary-driver/bpm-driver.js @@ -0,0 +1,35 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class BPMDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "BPM" + this.id = "bpm" + this.min = 1 + this.step = 1 + this.max = 240 + this.center = this.min + Object.assign(this, opts) + } + + toLocal(value) { + return value * 60 * 4 // length of one beat to bpm + } + + fromLocal(value) { + return value / 60 / 4 // bpm to length of one beat + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "bpm", + valueString: beautifyValue(rounded).value + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/exponent-driver.js b/dist/component/rotary-driver/exponent-driver.js new file mode 100644 index 0000000..c8d8321 --- /dev/null +++ b/dist/component/rotary-driver/exponent-driver.js @@ -0,0 +1,28 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class ExponentDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Exponent" + this.id = "exponent" + this.min = .5 + this.step = .01 + this.max = 1000 + this.scale = .2 + this.center = 1 + Object.assign(this, opts) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: beautifyValue(rounded).value + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/fraction-driver.js b/dist/component/rotary-driver/fraction-driver.js new file mode 100644 index 0000000..63de79c --- /dev/null +++ b/dist/component/rotary-driver/fraction-driver.js @@ -0,0 +1,47 @@ +import { fromFraction } from "../../math/from-fraction.js" +import toFraction from "../../math/to-fraction.js" +import RotaryDriver from "./rotary-driver.js" + +export default class FractionDriver extends RotaryDriver{ + tempo = 120 / 60 / 4 // length of one beat + constructor(opts) { + super() + this.name = "Fraction" + this.id = "fraction" + this.min = 1 / 64 + this.max = 1 + this.step = this.min + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return toFraction(this.max) + } + + get minLabel() { + return toFraction(this.min) + } + + toLocal(value) { + return value * this.tempo + } + + fromLocal(value) { + return value / this.tempo + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + //const rounded = this.round(limited) + const fractionStr = toFraction(limited) + const fractionVal = fromFraction(fractionStr) + return { + value: fractionVal, + precision: this.precisionString(local, fractionVal), + unit: "", + valueString: fractionStr + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/frequency-driver.js b/dist/component/rotary-driver/frequency-driver.js new file mode 100644 index 0000000..f222424 --- /dev/null +++ b/dist/component/rotary-driver/frequency-driver.js @@ -0,0 +1,46 @@ +import beautifyFrequency from "../../music/beautify-frequency.js" +import beautifyTime from "../../music/beautify-time.js" +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class FrequencyDriver extends RotaryDriver{ + constructor(opts) { + super() + this.name = "Frequency" + this.id = "frequency" + this.min = 1 + this.max = 22000 + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + const beautified = beautifyValue(this.max) + return `${beautified.value}${beautified.unit}` + } + + get minLabel() { + return beautifyTime(this.min).value + } + + toLocal(value) { + return 1/value + } + + fromLocal(value) { + return 1/value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const unitObject = beautifyFrequency(limited) + return { + value: this.round(limited), + precision: this.precisionString(local, limited), + unit: unitObject.unit, + valueString: unitObject.value + + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/gain-driver.js b/dist/component/rotary-driver/gain-driver.js new file mode 100644 index 0000000..c361b6a --- /dev/null +++ b/dist/component/rotary-driver/gain-driver.js @@ -0,0 +1,37 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class GainDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Gain" + this.id = "gain" + this.min = 0 + this.max = 1 + this.step = this.min + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return beautifyValue(this.max).value + } + + get minLabel() { + return beautifyValue(this.min).value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + const unitObject = beautifyValue(limited) + return { + value: limited, + precision: this.precisionString(local, rounded,.1), + unit: unitObject.unit, + valueString: unitObject.value + + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/grid-driver.js b/dist/component/rotary-driver/grid-driver.js new file mode 100644 index 0000000..6e86f70 --- /dev/null +++ b/dist/component/rotary-driver/grid-driver.js @@ -0,0 +1,39 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class GridDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Grid" + this.id = "grid" + this.min = 1 + this.step = 1 + this.max = 25 + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return "∞" + } + + toLocal(value) { + return value + } + + fromLocal(value) { + return value >= this.max ? Number.MAX_SAFE_INTEGER : value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: (rounded<=this.max-1)?this.precisionString(local, rounded):"", + unit: "", + valueString: (rounded>=this.max)?"∞":rounded + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/keys-driver.js b/dist/component/rotary-driver/keys-driver.js new file mode 100644 index 0000000..27b6e09 --- /dev/null +++ b/dist/component/rotary-driver/keys-driver.js @@ -0,0 +1,27 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class KeysDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Keys" + this.id = "keys" + this.min = 1 + this.step = 1 + this.max = 48 + this.center = this.min + Object.assign(this, opts) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/note-driver.js b/dist/component/rotary-driver/note-driver.js new file mode 100644 index 0000000..0e7588c --- /dev/null +++ b/dist/component/rotary-driver/note-driver.js @@ -0,0 +1,43 @@ +import { PIANO_KEYS, getNote, getNoteByIndex } from "../../music/notes.js" +import RotaryDriver from "./rotary-driver.js" + +export default class NoteDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Note" + this.id = "note" + this.min = 0 + this.max = PIANO_KEYS.length-1 + this.center = this.min + this.step = 1 + Object.assign(this, opts) + } + + get maxLabel() { + return `${PIANO_KEYS[this.max].name}${PIANO_KEYS[this.max].octave}` + } + + get minLabel() { + return `${PIANO_KEYS[this.min].name}${PIANO_KEYS[this.min].octave}` + } + + toLocal(value) { + return getNote(1/value).index + } + + fromLocal(value) { + return 1/getNoteByIndex(Math.round(value)).match + } + + render(value) { + const local = this.toLocal(value) + const note = getNote(1/value) + return { + value: local, + precision: note.precision === "=" ? "" : note.precision, + unit: "", + valueString: `${note.name.toUpperCase()}${note.octave}` + + } + } +} diff --git a/dist/component/rotary-driver/quantize-driver.js b/dist/component/rotary-driver/quantize-driver.js new file mode 100644 index 0000000..7b4f054 --- /dev/null +++ b/dist/component/rotary-driver/quantize-driver.js @@ -0,0 +1,40 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class QuantizeDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Quantize" + this.id = "quantize" + this.min = 1 + this.step = 1 + this.scale = .5 + this.max = 1025 + this.center = 1025 + Object.assign(this, opts) + } + + get maxLabel() { + return "∞" + } + + toLocal(value) { + return value + } + + fromLocal(value) { + return value >= this.max ? Number.MAX_SAFE_INTEGER : value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: (rounded<=this.max-1)?this.precisionString(local, rounded):"", + unit: "", + valueString: (rounded>=this.max)?"∞":rounded + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/range-driver.js b/dist/component/rotary-driver/range-driver.js new file mode 100644 index 0000000..6cee638 --- /dev/null +++ b/dist/component/rotary-driver/range-driver.js @@ -0,0 +1,35 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class RangeDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "FM Range" + this.id = "range" + this.min = 0 + this.step = 1 + this.max = 48 + this.center = 1 + Object.assign(this, opts) + } + + toLocal(value) { + return ((value - 1) * 12) //((value/2) * 12) // from multiplicator base to notes + } + + fromLocal(value) { + return (value / 12)+1 // (value / 12) * 2 // from notes to multiplicator base + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/rotary-driver.js b/dist/component/rotary-driver/rotary-driver.js new file mode 100644 index 0000000..547bca2 --- /dev/null +++ b/dist/component/rotary-driver/rotary-driver.js @@ -0,0 +1,60 @@ +export default class RotaryDriver { + min = 0 + max = 1 + center = 0 + step = 0 + name = "" + id = "default" + scale = 1 + + constructor(opts) { + Object.assign(this, opts) + } + + precisionString(value, reference, precision=0.001) { + if (value < this.min) { + return "<" + } else if (value > this.max) { + return ">" + } else if (Math.round(value * precision) == Math.round(reference * precision)){ + return "" + } else { + return "≈" + } + } + + limit(value) { + return Math.min(this.max, Math.max(this.min, value)) + } + + round(value) { + if (this.step == 0) return value + return Math.round(value * 1 / this.step) * this.step + } + + toLocal(value) { + return value + } + + fromLocal(value) { + return value + } + + get maxLabel() { + return this.max + } + + get minLabel() { + return this.min + } + + render(value) { + const local = this.toLocal(value) + return { + value: local, + precision: "", + unit: "", + valueString: local + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/subdivision-driver.js b/dist/component/rotary-driver/subdivision-driver.js new file mode 100644 index 0000000..7d0bfb4 --- /dev/null +++ b/dist/component/rotary-driver/subdivision-driver.js @@ -0,0 +1,26 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class SubdivisionDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Subdivisions" + this.min = 1 + this.step = 1 + this.max = 60 + this.center = this.min + Object.assign(this, opts) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-driver/time-driver.js b/dist/component/rotary-driver/time-driver.js new file mode 100644 index 0000000..e6081fd --- /dev/null +++ b/dist/component/rotary-driver/time-driver.js @@ -0,0 +1,39 @@ +import beautifyTime from "../../music/beautify-time.js" +import RotaryDriver from "./rotary-driver.js" + +export default class TimeDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Time" + this.id = "time" + this.min = 1/20000 + this.max = 60 + this.step = this.min + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + const beautified = beautifyTime(this.max) + return `${beautified.value}${beautified.unit}` + } + + get minLabel() { + const beautified = beautifyTime(this.min) + return `${beautified.value*1000}μs` + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + const unitObject = beautifyTime(limited) + return { + value: limited, + precision: this.precisionString(local, rounded,.1), + unit: unitObject.unit, + valueString: unitObject.value + + } + } +} \ No newline at end of file diff --git a/dist/component/rotary-group.css b/dist/component/rotary-group.css new file mode 100644 index 0000000..1c4a611 --- /dev/null +++ b/dist/component/rotary-group.css @@ -0,0 +1,10 @@ +:host { + user-select: none; + display: flex; + flex-wrap: wrap; + white-space: nowrap; + overflow: hidden; + gap: 6px; + box-sizing: border-box; + flex-direction: row; +} \ No newline at end of file diff --git a/dist/component/rotary-group.js b/dist/component/rotary-group.js new file mode 100644 index 0000000..37a0373 --- /dev/null +++ b/dist/component/rotary-group.js @@ -0,0 +1,166 @@ +import Component from "./component.js" +import Display from "./display.js" +import RotaryDriver from "./rotary-driver/rotary-driver.js" +import Rotary from "./rotary.js" + + +export default class RotaryGroup extends Component { + + static CHANGE = 'change' + static DRIVER_CHANGE = 'driver-change' + static style = 'component/rotary-group.css' + + + #rotary = Rotary.create() + #display = Display.create() + #value + + + #drivers = [RotaryDriver] + #driver = RotaryDriver.id + + + constructor() { + super() + this.intitialized = false + this.shadowRoot.append(this.#rotary) + this.shadowRoot.append(this.#display) + + this.#rotary.addEventListener(Rotary.CHANGE, this.binding(this.#onRotaryChange)) + this.#display.addEventListener(Display.UP, this.binding(this.#onDisplayClick)) + + this.#init() + } + + async #init() { + await this.appendStyleLink(RotaryGroup.style) + this.intitialized = true + this.#updateValue() + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #onRotaryChange(e) { + if (this.#driver) { + this.#value = this.#driver.fromLocal(this.#rotary.value) + } + } + + #onDisplayClick(e) { + this.nextDriver() + } + + nextDriver() { + const index = (this.#drivers.indexOf(this.#driver) + 1) % this.#drivers.length + this.driver = this.#drivers[index].id + this.dispatchEvent( + new CustomEvent( + RotaryGroup.DRIVER_CHANGE, { + bubbles: true, + composed: true + } + ) + ) + } + + previousDriver() { + const index = (this.#drivers.indexOf(this.#driver) + this.#drivers.length - 1) % this.#drivers.length + this.driver = this.#drivers[index].id + this.dispatchEvent( + new CustomEvent( + RotaryGroup.DRIVER_CHANGE, { + bubbles: true, + composed: true + } + ) + ) + } + + set drivers(value) { + this.#drivers = value + if (this.driver) this.driver = this.#driver.id + else this.driver = this.#drivers[0].id + this.#updateDrivers() + } + + get drivers() { + return this.#drivers + } + + set driver(id) { + this.#driver = this.#drivers.find((driver)=>{return driver.id === id}) + this.#updateLabels() + this.#updateValue() + this.#updateDrivers() + } + + get driver() { + if (!this.#driver) return "" + return this.#driver.id + } + + set value(value) { + this.#value = value + this.#updateValue() + } + + get value() { + return this.#value + + } + + get rotary() { + return this.#rotary + } + + #updateDrivers() { + + this.#display.modes = this.#drivers.map(driver=>driver.name) + this.#display.mode = this.#driver.name + + } + + #updateLabels() { + if (this.#driver) { + this.#rotary.min = this.#driver.min + this.#rotary.center = this.#driver.center + this.#rotary.minLabel = this.#driver.minLabel + this.#rotary.max = this.#driver.max + this.#rotary.step = this.#driver.step + this.#rotary.maxLabel = this.#driver.maxLabel + this.#rotary.header = this.#driver.name + this.#rotary.scale = this.#driver.scale + + if (this.#drivers.length > 1) { + this.#display.clickable = true + this.#display.footer = `Mode: ${this.#drivers.indexOf(this.#driver)+1}/${this.#drivers.length}` + } else { + this.#display.clickable = false + this.#display.footer = "" + + } + } + } + + #updateValue() { + if (this.#driver) { + const valueSet = this.#driver.render(this.#value) + this.#display.precision = valueSet.precision + this.#display.unit = valueSet.unit + this.#display.value = valueSet.valueString + this.#rotary.value = valueSet.value + } + } + + #renderCanvas() { + + } + + destroy() { + this.#rotary.removeEventListener(Rotary.CHANGE, this.binding(this.#onRotaryChange)) + this.#display.removeEventListener(Display.UP, this.binding(this.#onDisplayClick)) + this.#rotary.destroy() + this.#display.destroy() + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/rotary.css b/dist/component/rotary.css new file mode 100644 index 0000000..5f1faf7 --- /dev/null +++ b/dist/component/rotary.css @@ -0,0 +1,39 @@ +:host { + user-select: none; + display: flex; + width: 90px; + height: 72px; + white-space: nowrap; + /*overflow: hidden;*/ + box-sizing: border-box; + touch-action: none; + flex-direction: column; + flex:0; + padding: 6px; + cursor: pointer; +} + +canvas { + touch-action: none; + display:flex; + height: 36px; + width: 78px; +} + +.header, .footer{ + font-family: sans-serif; + color:#909090; + font-size: 9px; + height: 12px; + line-height: 12px; +} + +.header { + align-self: flex-start; +} + +.footer { + display: flex; + justify-content: space-between; + flex-direction: row; +} diff --git a/dist/component/rotary.js b/dist/component/rotary.js new file mode 100644 index 0000000..0318532 --- /dev/null +++ b/dist/component/rotary.js @@ -0,0 +1,359 @@ + +import hslToRgb from "../color/hsl-to-rgb.js" +import rgbaToCss from "../color/rgba-to-css.js" +import calculateAngleBetween from "../math/calculate-angle-between.js" +import calculateAngle from "../math/calculate-angle.js" +import calculateCirclePoint from "../math/calculate-circle-point.js" +import { TAU } from "../math/contants.js" +import translatePoint from "../math/translate-point.js" +import wrapAngle from "../math/wrap-angle.js" +import Component from "./component.js" + +export default class Rotary extends Component { + + static CHANGE = 'change' + static style = 'component/rotary.css' + + #canvas = document.createElement('canvas') + #ctx + + #angleOffset = -Math.PI/2 + #fromAngle = -.8 * Math.PI + #toAngle = .8 * Math.PI + #value = 0 + #min = -1 + #max = 1 + #center = 0 + //#paddingFactor = .2 + #padding = 5 + #labelSpacing = 14 + #step = 0 + #radius + #diameter + #width + #height + #innerRadius + #segmentAngle + #segmentHeight + #perimeterColor = hslToRgb({h: 0, s: 0, l: 1}) + #backgroundColor = hslToRgb({h: 0, s: 0, l: .5}) + #handleColor = hslToRgb({h: 0, s: 0, l: 1}) + #lineWidth = 2 + #handleRadius = 3 + #minLabel = "" + #maxLabel = "" + #header = "" + #footer = "" + #headerEl = document.createElement("div") + #footerEl = document.createElement("div") + #minEl = document.createElement("div") + #maxEl = document.createElement("div") + + #scale = 1 + + #isDown + + constructor() { + super() + this.intitialized = false + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 78) + this.#canvas.setAttribute("height", 36) + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + + this.#footerEl.classList.add("footer") + this.#minEl.classList.add("min") + this.#footerEl.append(this.#minEl) + this.#maxEl.classList.add("max") + this.#footerEl.append(this.#maxEl) + this.shadowRoot.append(this.#footerEl) + + this.#init() + } + + async #init() { + await this.appendStyleLink(Rotary.style) + this.#calculate() + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointermove", this.binding(this.#onPointerMove)) + this.addEventListener("pointercancel", this.binding(this.#onPointerCancel)) + this.addEventListener("lostpointercapture", this.binding(this.#onPointerLost)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.intitialized = true + } + + + #onPointerDown(e) { + if (this.#isDown) return + if (e.button != 0) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + if (e.button != 0) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerCancel(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerLost(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerMove(e) { + if (this.#isDown !== e.pointerId) return + this.#positionFromEvent(e) + } + + #positionFromEvent(e) { + let rect = this.#canvas.getBoundingClientRect(); + let x = e.clientX - rect.left + let y = e.clientY - rect.top + + // proportional + let p = { + x: ((x - this.#canvas.width / 2) / this.radius), + y: ((y - this.#canvas.height / 2) / this.radius) + } + let w = this.#canvas.width + let h = this.#canvas.height + + const angle = calculateAngle(p) - this.#angleOffset + + + let start = wrapAngle(this.#fromAngle) + let end = wrapAngle(this.#toAngle) + let range = calculateAngleBetween(this.#fromAngle, this.#toAngle) + let value = calculateAngleBetween(start, angle) + let propValue = value / range + let inverseRange = TAU - range + //this.#value = Math.min(1,Math.max(0, propValue)) + let result + if (propValue < 1+inverseRange/TAU/2) { + result = Math.min(1, propValue) + } else if (propValue > 1+inverseRange/TAU/2) { + result = 0 + } else { + result = Math.min(1, Math.max(0, propValue)) + } + + if (this.#scale != 1) { + result = Math.pow(result, 1/this.#scale) + } + + this.#value = result + + this.addToRenderQueue(this.binding(this.#renderCanvas)) + this.dispatchEvent( + new CustomEvent( + Rotary.CHANGE, + { + composed: true + } + ) + ) + } + + get value() { + let result = this.#value * (this.#max-this.#min) + this.#min + if (this.step > 0) { + result = Math.round(result / this.step) * this.step + } + return result + } + + + + set value(value) { + this.#value = Math.max(0, Math.min(1,(value - this.#min) / (this.#max-this.#min))) + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + + get step() { + return this.#step + } + + set step(value) { + this.#step = value + } + + + get min() { + return this.#min + } + + set min(value) { + this.#min = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get minLabel() { + return this.#minLabel + } + + set minLabel(value) { + this.#minLabel = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get max() { + return this.#max + } + + set max(value) { + this.#max = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get maxLabel() { + return this.#maxLabel + } + + set maxLabel(value) { + this.#maxLabel = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get center() { + return this.#center + } + + set center(value) { + this.#center = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get scale() { + return this.#scale + } + + set scale(value) { + this.#scale = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + set angleOffset(value) { + this.#angleOffset = Math.max(1, value) + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get angleOffset() { + return this.#angleOffset + } + + get radius() { + return this.#radius + } + + get diameter() { + return this.#diameter + } + + get header() { + return this.#header + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + + + #calculate() { + this.#diameter = Math.min( + this.#canvas.width - this.#padding * 2, + this.#canvas.height - this.#padding * 2 + ) + this.#radius = this.#diameter / 2 + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #renderCanvas() { + + let w = this.#canvas.width + let h = this.#canvas.height + if (!w || !h) return console.log(w,h) + let c = {x: w/2, y: h/2} + + let val = Math.max(0, Math.min(1,(this.value - this.#min) / (this.#max-this.#min))) + + if (this.#scale != 1) { + val = Math.pow(val, this.#scale) + } + + let start = this.#fromAngle + this.#angleOffset + let end = this.#toAngle + this.#angleOffset + let overallRange = calculateAngleBetween(start, end) + let range = overallRange * val + + let valueAngle = start + range + + this.#ctx.clearRect(0, 0, this.#canvas.width, this.#canvas.height) + this.#ctx.save() + + // circle + this.#ctx.beginPath(); + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.strokeStyle = "#909090" // rgbaToCss(this.#backgroundColor) + this.#ctx.arc(c.x, c.y, this.radius, start, end); + this.#ctx.stroke(); + + // circle + this.#ctx.beginPath(); + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.strokeStyle = rgbaToCss(this.#perimeterColor) + + let valRange = Math.abs(this.#max - this.#min) + let propCenter = (this.#center-this.#min) / valRange + let centerAngle = start + (propCenter * overallRange) + let ccw = (centerAngle > valueAngle) + + this.#ctx.arc(c.x, c.y, this.radius, centerAngle, valueAngle, ccw); + this.#ctx.stroke(); + + + let s = translatePoint(calculateCirclePoint(this.radius, valueAngle), c) + // handle + this.#ctx.save() + this.#ctx.beginPath(); + this.#ctx.fillStyle = rgbaToCss(this.#handleColor) + this.#ctx.arc(s.x , s.y, this.#handleRadius, 0, 2 * Math.PI); + this.#ctx.fill(); + + this.#ctx.restore() + + this.#headerEl.textContent = this.#header + + const minLabel = this.minLabel || this.min + const maxLabel = this.maxLabel || this.max + this.#minEl.textContent = minLabel + this.#maxEl.textContent = maxLabel + + } + + destroy() { + + this.#canvas.removeEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + this.#canvas.removeEventListener("pointerup", this.binding(this.#onPointerUp)) + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/session-editor.css b/dist/component/session-editor.css new file mode 100644 index 0000000..4fa98ce --- /dev/null +++ b/dist/component/session-editor.css @@ -0,0 +1,18 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} +.container { + flex-direction: column; + max-width: 100%; +} \ No newline at end of file diff --git a/dist/component/session-editor.js b/dist/component/session-editor.js new file mode 100644 index 0000000..3e59820 --- /dev/null +++ b/dist/component/session-editor.js @@ -0,0 +1,171 @@ + +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Dynamics from "../model/dynamics.js" +import Session from "../model/session.js" +import SessionMix from "./session-mix.js" +import Component from "./component.js" +import KeyboardSettingsEditor from "./keyboard-settings-editor.js" +import Button from "./button.js" +import BeatDriver from "./rotary-driver/beat-driver.js" +import BPMDriver from "./rotary-driver/bpm-driver.js" +import RotaryGroup from "./rotary-group.js" + +export default class SessionEditor extends Component { + static SOLO = 'solo' + static ZERO = 'zero' + static CHANGE = 'change' + static style = 'component/session-editor.css' + + + #stateToggle = Button.create() + #zeroButton = Button.create() + + #tempo = RotaryGroup.create() + #channelMix = SessionMix.create() + #keyboardSettingsEditor = KeyboardSettingsEditor.create() + #session + + #siblingsToggle = Button.create() + + + constructor() { + super() + this.intitialized = false + + + this.#stateToggle.header = "State" + this.#stateToggle.mode = "toggle" + this.shadowRoot.append(this.#stateToggle) + this.#stateToggle.addEventListener(Button.UP, this.binding(this.#onStateToggle)) + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + + + this.#tempo.drivers = [ + new BPMDriver(), + new BeatDriver({name:"Beat length"}) + ] + + this.#tempo.addEventListener(RotaryGroup.DRIVER_CHANGE, this.binding(this.#onTempoDriverChange)) + this.shadowRoot.append(this.#tempo) + + + this.shadowRoot.append(this.#channelMix) + + this.shadowRoot.append(this.#keyboardSettingsEditor) + + + + this.#siblingsToggle.header = "View Navigation" + this.#siblingsToggle.mode = "toggle" + this.#siblingsToggle.addEventListener(Button.UP, this.binding(this.#onSiblingsToggle)) + this.shadowRoot.append(this.#siblingsToggle) + + + this.#tempo.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onTempoChange)) + + + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + + #onTempoChange(e) { + this.#session.settings.tempo = this.#tempo.value + } + #onTempoDriverChange(e) { + this.#session.settings.tempoDriver = this.#tempo.driver + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + SessionEditor.ZERO, + { + composed: true, + detail: this.#session.id + } + ) + ) + } + + #onStateToggle(e) { + if ( + this.#session.state === Session.PLAYING + || this.#session.state === Session.PLAY + || this.#session.state === Session.TRIGGER_PLAY + ) { + this.#session.state = Session.TRIGGER_PAUSE + } else if ( + this.#session.state === Session.PAUSED + || this.#session.state === Session.TRIGGER_PAUSE + || this.#session.state === Session.PAUSE + ) { + this.#session.state = Session.TRIGGER_PLAY + } + } + + #onSiblingsToggle(e) { + if (this.#session.navigationMode === Session.COMPACT) { + this.#session.navigationMode = Session.MULTILINE + } else if (this.#session.navigationMode === Session.MULTILINE) { + this.#session.navigationMode = Session.SIBLINGS + } else { + this.#session.navigationMode = Session.COMPACT + } + } + + async #init() { + await this.appendStyleLink(SessionEditor.style) + this.intitialized = true + } + + set session(value) { + this.#session = value + this.#channelMix.session = this.#session + this.#keyboardSettingsEditor.session = this.#session + this.#update() + } + + get session() { + return this.#session + } + + + #onSessionChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + || signal.path[0].property === "state" + || signal.path[0].property === "tempo" + || signal.path[0].property === "tempoDriver" + || signal.path[0].property === "showSiblings" + ) this.#update() + } + + #update() { + if (this.#session) { + + + if (this.#session.settings.tempoDriver) this.#tempo.driver = this.#session.settings.tempoDriver + + + this.#stateToggle.label = this.#session.state + this.#siblingsToggle.label = this.#session.navigationMode + this.#tempo.value = this.#session.settings.tempo + } + + } + + destroy() { + unwatch(this, "settings", this.binding(this.#onSessionChange)) + super.destroy() + + } + +} \ No newline at end of file diff --git a/dist/component/session-mix.css b/dist/component/session-mix.css new file mode 100644 index 0000000..8b245f2 --- /dev/null +++ b/dist/component/session-mix.css @@ -0,0 +1,19 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} + +.container { + flex-direction: column; + max-width: 100%; +} \ No newline at end of file diff --git a/dist/component/session-mix.js b/dist/component/session-mix.js new file mode 100644 index 0000000..efde357 --- /dev/null +++ b/dist/component/session-mix.js @@ -0,0 +1,148 @@ + +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Dynamics from "../model/dynamics.js" +import Button from "./button.js" +import Component from "./component.js" +import MetricsDisplay from "./metrics-display.js" +import MultiPoleFader from "./multi-pole-fader.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import RotaryGroup from "./rotary-group.js" + +export default class SessionMix extends Component { + + static CHANGE = 'change' + static style = 'component/session-mix.css' + + + #soloToggle = Button.create() + #metricsDisplay = MetricsDisplay.create() + #channelMix = MultiPoleFader.create() + #gainRotary = RotaryGroup.create() + #potentialRotary = RotaryGroup.create() + #thresholdRotary = RotaryGroup.create() + #scaleRotary = RotaryGroup.create() + #session + + + constructor() { + super() + this.intitialized = false + + this.#soloToggle.header = "Solo" + this.#soloToggle.mode = "toggle" + this.shadowRoot.append(this.#soloToggle) + this.#soloToggle.addEventListener(Button.UP, this.binding(this.#onSoloToggle)) + + this.shadowRoot.append(this.#metricsDisplay) + + this.#channelMix.addEventListener(MultiPoleFader.CHANGE, this.binding(this.#onMixChange)) + this.shadowRoot.append(this.#channelMix) + + this.#gainRotary.drivers = [ + new GainDriver({name:"Main Volume"}) + ] + this.shadowRoot.append(this.#gainRotary) + + /*this.#potentialRotary.drivers = [ + new GainDriver({name:"Potential"}) + ] + this.shadowRoot.append(this.#potentialRotary)*/ + + + this.#thresholdRotary.drivers = [ + new GainDriver({name: "Squeeze Threshold"}) + ] + this.shadowRoot.append(this.#thresholdRotary) + + + this.#scaleRotary.drivers = [ + new GainDriver({name: "Squeeze Scale", max: 4}) + ] + this.shadowRoot.append(this.#scaleRotary) + + + + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + #onSoloToggle(e) { + this.#session.voiceSolo("") + } + + #onGainChange(e) { + this.#session.main = this.#gainRotary.value + } + + #onPotentialChange(e) { + this.#session.dynamics.potential = this.#potentialRotary.value + } + #onThresholdChange(e) { + this.#session.dynamics.threshold = this.#thresholdRotary.value + } + #onScaleChange(e) { + this.#session.dynamics.scale = this.#scaleRotary.value + } + + #onMixChange(e) { + + this.#session.channelMix.x = this.#channelMix.position.x + this.#session.channelMix.y = this.#channelMix.position.y + + } + + + async #init() { + await this.appendStyleLink(SessionMix.style) + + this.#gainRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGainChange)) + this.#potentialRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onPotentialChange)) + this.#thresholdRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onThresholdChange)) + this.#scaleRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onScaleChange)) + this.intitialized = true + } + + get session() { + return this.#session + } + + set session(value) { + this.#session = value + this.#metricsDisplay.audioMetrics = this.#session.audioMetrics + this.#update() + } + + #onSessionChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + || signal.path.length == 1 + ) this.#update() + } + + #update() { + this.#gainRotary.value = this.#session.main + this.#channelMix.poles = this.#session.channels.length + this.#channelMix.position.x = this.#session.channelMix.x + this.#channelMix.position.y = this.#session.channelMix.y + this.#potentialRotary.value = this.#session.dynamics.potential + this.#scaleRotary.value = this.#session.dynamics.scale + this.#thresholdRotary.value = this.#session.dynamics.threshold + if (this.#session.solo === "") { + this.#soloToggle.label = "off" + this.#soloToggle.mode = "inactive" + } else { + this.#soloToggle.label = "on" + this.#soloToggle.mode = "solo" + } + + + } + + destroy() { + unwatch(this, "session", this.binding(this.#onSessionChange)) + super.destroy() + + } + +} \ No newline at end of file diff --git a/dist/component/splash-screen-animation.css b/dist/component/splash-screen-animation.css new file mode 100644 index 0000000..5ce6a9c --- /dev/null +++ b/dist/component/splash-screen-animation.css @@ -0,0 +1,67 @@ +:host { + position: relative; + display: flex; + align-items: center; + flex-direction: column; + box-sizing: border-box; + justify-content: space-between; + width: 282px; + height: 228px; +} + +:host(.logo) { + background-color: #112233; +} + + +:host(.icon) { + background-color: #001422; +} + +.header { + display: flex; + font-size: 12px; + min-height: 12px; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-start; + overflow: hidden; + padding: 6px; + color: rgba(255,255,255,1); +} + +.label { + display: flex; + font-size: 48px; + font-weight: bold; + flex-wrap: wrap; + word-wrap: break-word; + white-space: normal; + color: rgba(255,255,255,1); +} + +.canvas { + width: 282px; + height: 228px; + position: absolute; +} + +:host(.icon) .label { + color: rgba(255,255,255,1); + /*backdrop-filter: blur(10px);*/ + font-size: 42px; +} + +.footer { + display: flex; + font-size: 12px; + min-height: 12px; + max-width: 100%; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-end; + overflow: hidden; + text-align: right; + padding: 6px; + color: rgba(255,255,255,1); +} \ No newline at end of file diff --git a/dist/component/splash-screen-animation.js b/dist/component/splash-screen-animation.js new file mode 100644 index 0000000..14a2eb1 --- /dev/null +++ b/dist/component/splash-screen-animation.js @@ -0,0 +1,227 @@ + +import rgbaToCss from "../color/rgba-to-css.js" +import WaveSpline from "../model/wave-spline.js" +import solveWaveSpline from "../wave-spline/solve-wave-spline.js" +import Component from "./component.js" + +export default class SplashScreenAnimation extends Component { + + static style = 'component/splash-screen-animation.css' + static UP = 'up' + static DOWN = 'down' + + #header = "" + #footer = "" + #label = "" + + #mode = "logo" + + #ctx + + #canvasEl = document.createElement("canvas") + #headerEl = document.createElement("div") + #labelEl = document.createElement("div") + #footerEl = document.createElement("div") + + #isDown + + + constructor() { + super() + this.intitialized = false + + this.#canvasEl.classList.add("canvas") + this.#ctx = this.#canvasEl.getContext("2d") + this.shadowRoot.append(this.#canvasEl) + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.#labelEl.classList.add("label") + this.shadowRoot.append(this.#labelEl) + + + this.#footerEl.classList.add("footer") + this.shadowRoot.append(this.#footerEl) + + this.#dataset = this.#generate() + + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.#init() + } + + async #init() { + await this.appendStyleLink(SplashScreenAnimation.style) + this.intitialized = true + this.#render() + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenAnimation.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenAnimation.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get header() { + return this.#header + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get label() { + return this.#label + } + + set footer(value) { + this.#footer = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get footer() { + return this.#footer + } + + set mode(value) { + this.#mode = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get mode() { + return this.#mode + } + + #update() { + + this.classList.add("icon") + this.#headerEl.textContent = this.#header + this.#labelEl.textContent = this.#label + this.#footerEl.textContent = this.#footer + + } + + #layers = 7 + #minPoints = 4 + #maxPoints = 7 + + #generate() { + const layers = [] + for (let l = 0; l < this.#layers; l++) { + const points = this.#minPoints + Math.random() * (this.#maxPoints - this.#minPoints) + const layer = [] + for (let p = 0; p < points-1; p++) { + layer.push({x: 1/points*p, y: Math.random(), e: 2.341}) // 1 + Math.random() * 2}) + } + layers.push(new WaveSpline({points:layer})) + } + return layers + } + + #dataset = [] + + #maxV = 0.001 + #minA = 0.000007 + #maxA = 0.0007 + + #minPhase = .000007 + #maxPhase = .0007 + + #render() { + requestAnimationFrame(()=>{ + const d = this.#canvasEl.getBoundingClientRect() + if (this.#canvasEl.width != d.width) this.#canvasEl.width = d.width + if (this.#canvasEl.height != d.height) this.#canvasEl.height = d.height + const h = d.height *.5 + const oy = d.height * 0.25 + this.#ctx.clearRect(0,0, d.width, d.height) + this.#ctx.save() + this.#ctx.globalCompositeOperation = "screen"; + for (let i = 0; i.5?1:-1 + let p = null + this.#ctx.beginPath() + + const grd = this.#ctx.createLinearGradient(0, 0, 0, d.height); + grd.addColorStop(0.0, rgbaToCss({r:0,g:0,b:0,a:i/this.#dataset.length * .01}) ); + grd.addColorStop(0.5, rgbaToCss({r:255,g:255,b:255,a:i/this.#dataset.length * .05}) ); + grd.addColorStop(1, rgbaToCss({r:0,g:0,b:0,a:i/this.#dataset.length * .01}) ); + this.#ctx.fillStyle = grd + this.#ctx.lineWidth = 2 + if (this.#dataset[i].direction < 0) this.#ctx.moveTo(-2, -2) + else this.#ctx.moveTo(-2, d.height+2) + + for (let x = 0; x < d.width; x++) { + let y = solveWaveSpline(this.#dataset[i], (x/d.width + this.#dataset[i].phase + 1)%1) + + let c = {x: x, y: y*h + oy} + this.#ctx.lineTo(c.x, c.y) + + } + if (this.#dataset[i].direction < 0) this.#ctx.lineTo(d.width+2, -2) + else this.#ctx.lineTo(d.width+2, d.height+2) + + this.#ctx.closePath() + this.#ctx.fill() + + + if (!this.#dataset[i].vp) { + this.#dataset[i].vp = this.#minPhase + Math.random() * (this.#maxPhase - this.#minPhase) + if (Math.random()>0.5) this.#dataset[i].vp *=-1 + } + this.#dataset[i].phase = (this.#dataset[i].phase + this.#dataset[i].vp + 1) % 1 + for (let p = 0; p < this.#dataset[i].points.length; p++) { + if (!this.#dataset[i].points[p].vy) { + this.#dataset[i].points[p].vy = this.#minA + Math.random() * (this.#maxA -this.#minA) + if (Math.random()>0.5) this.#dataset[i].points[p].vy *=-1 + } + if ( this.#dataset[i].points[p].y + this.#dataset[i].points[p].vy > 1 || this.#dataset[i].points[p].y + this.#dataset[i].points[p].vy < 0) this.#dataset[i].points[p].vy *= -1 + this.#dataset[i].points[p].y = Math.max(0, Math.min(1, (this.#dataset[i].points[p].y + this.#dataset[i].points[p].vy))) + } + + } + + this.#ctx.restore() + + this.#render() + }) + + } + + destroy() { + super.destroy() + + } +} \ No newline at end of file diff --git a/dist/component/splash-screen-item.css b/dist/component/splash-screen-item.css new file mode 100644 index 0000000..830ca0d --- /dev/null +++ b/dist/component/splash-screen-item.css @@ -0,0 +1,53 @@ +:host { + display: flex; + align-items: center; + flex-direction: column; + box-sizing: border-box; + justify-content: space-between; + padding: 6px; + width: 282px; + height: 228px; +} + +:host(.logo) { + background-color: #121212; + color: #909090; + cursor: pointer; +} + +:host(.icon) { + background-color: #061422; +} + +.header { + display: flex; + font-size: 12px; + text-wrap: pretty; + min-height: 12px; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-start; + overflow: hidden; +} + +.label { + display: flex; + font-size: 12px; + flex: 1; + font-weight: normal; + flex-wrap: wrap; + word-wrap: break-word; + white-space: pre-line; +} + +.footer { + display: flex; + font-size: 12px; + min-height: 12px; + max-width: 100%; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-end; + overflow: hidden; + text-align: right; +} \ No newline at end of file diff --git a/dist/component/splash-screen-item.js b/dist/component/splash-screen-item.js new file mode 100644 index 0000000..b1e3b94 --- /dev/null +++ b/dist/component/splash-screen-item.js @@ -0,0 +1,129 @@ + +import Component from "./component.js" + +export default class SplashScreenItem extends Component { + + static style = 'component/splash-screen-item.css' + static UP = 'up' + static DOWN = 'down' + + #label = "" + #header = "" + #footer = "" + + #mode = "default" + + #labelEl = document.createElement("div") + #headerEl = document.createElement("div") + #footerEl = document.createElement("div") + + #isDown + + + constructor() { + super() + this.intitialized = false + + + this.#labelEl.classList.add("label") + this.#labelEl.textContent = "AWSM" + this.shadowRoot.append(this.#labelEl) + + this.#footerEl.classList.add("footer") + this.#footerEl.textContent = "MKII" + this.shadowRoot.append(this.#footerEl) + + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.#init() + } + + async #init() { + await this.appendStyleLink(SplashScreenItem.style) + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenItem.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenItem.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get label() { + return this.#label + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get header() { + return this.#header + } + + set footer(value) { + this.#footer = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get footer() { + return this.#footer + } + + set mode(value) { + this.#mode = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get mode() { + return this.#mode + } + + #render() { + + if (this.#mode === "logo") this.classList.add("logo") + else this.classList.remove("logo") + if (this.#mode === "icon") this.classList.add("icon") + else this.classList.remove("icon") + + this.#labelEl.textContent = this.#label + this.#headerEl.textContent = this.#header + this.#footerEl.textContent = this.#footer + + } + + destroy() { + super.destroy() + + } +} \ No newline at end of file diff --git a/dist/component/splash-screen.css b/dist/component/splash-screen.css new file mode 100644 index 0000000..3a1d3f8 --- /dev/null +++ b/dist/component/splash-screen.css @@ -0,0 +1,22 @@ +:host { + font-family: sans-serif; + color: #FFFFFF; + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + overflow: hidden; +} + +.container { + display: flex; + align-items: center; + flex-direction: row; + box-sizing: border-box; + justify-content: center; + flex-wrap: wrap; + gap: 6px; + min-height: 180px; +} + diff --git a/dist/component/splash-screen.js b/dist/component/splash-screen.js new file mode 100644 index 0000000..b9f5b27 --- /dev/null +++ b/dist/component/splash-screen.js @@ -0,0 +1,58 @@ +import Component from "./component.js" +import SplashScreenAnimation from "./splash-screen-animation.js" +import SplashScreenItem from "./splash-screen-item.js" + +export default class SplashScreen extends Component { + + static DISMISS = "dismiss" + static style = 'component/splash-screen.css' + + #container = document.createElement("div") + #info = SplashScreenItem.create() + #logo = SplashScreenAnimation.create() + + constructor() { + super() + this.intitialized = false + + this.#container.classList.add("container") + this.shadowRoot.append(this.#container) + + this.#logo.header = "" + this.#logo.label = "AWSM" + this.#logo.footer = "" + this.#logo.mode = "icon" + this.#container.append(this.#logo) + + this.#info.label = "AwesomeWaveSplineMachine MKII\n\nTo continue, you must agree that your browser's database is used to persist your sessions. All your actions will be saved automatically.\n\nBe careful, this software is theoretically capable of destroying your precious speakers.\n\nUse on your own risk!" + this.#info.footer = "Click to agree and continue" + this.#info.mode = "logo" + this.#container.append(this.#info) + + + this.#info.addEventListener(SplashScreenItem.UP, this.binding(this.#onPointerUp)) + this.#init() + } + + async #init() { + await this.appendStyleLink(SplashScreen.style) + this.intitialized = true + } + + #onPointerUp(e) { + this.dispatchEvent( + new CustomEvent( + SplashScreen.DISMISS, + { + bubbles: true, + composed: true + } + ) + ) + } + + destroy() { + super.destroy() + + } +} \ No newline at end of file diff --git a/dist/component/view-editor.css b/dist/component/view-editor.css new file mode 100644 index 0000000..5e3c690 --- /dev/null +++ b/dist/component/view-editor.css @@ -0,0 +1,59 @@ +:host { + user-select: none; + display: flex; + min-width: 102px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + max-width: 100%; + flex-direction: column; +} + +.status-indicator{ + height: 6px; + background-color: #121212; + margin-right: 12px; + +} + +.status-indicator.active { + background-color: #FFFFFF; + +} + +.container { + display: flex; + flex-direction: column; + overflow-x: hidden; + overflow-y: auto; + margin: 6px 0px 6px 0px; + padding-right: 6px; + gap: 6px; + flex: 1; +} + +/* Style the scrollbar background */ +::-webkit-scrollbar { + width: 6px; + height: 6px; + background: #000000; +} + +/* Style the scrollbar handle */ +::-webkit-scrollbar-thumb { + background: #303030; + border-radius: 0px; +} + +.mix { + display: flex; + flex-direction: column; +} + +.list { + display: flex; + flex-direction: column; + flex: 1; + max-width: 100%; +} \ No newline at end of file diff --git a/dist/component/view-editor.js b/dist/component/view-editor.js new file mode 100644 index 0000000..7fbfbee --- /dev/null +++ b/dist/component/view-editor.js @@ -0,0 +1,148 @@ +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import ChannelEditor from "./channel-editor.js" +import Component from "./component.js" +import ViewNavigation from "./view-navigation.js" +import OscillatorEditor from "./oscillator-editor.js" +import SessionEditor from "./session-editor.js" +import VoiceEditor from "./voice-editor.js" + +export default class ViewEditor extends Component { + + static CHANGE = 'change' + static style = 'component/view-editor.css' + + #container = document.createElement('div') + #content = document.createElement('div') + #navigation = ViewNavigation.create() + #settingsEditor = SessionEditor.create() + #channelEditor = ChannelEditor.create() + #voiceEditor = VoiceEditor.create() + #oscillatorEditor = OscillatorEditor.create() + #statusIndicator = document.createElement("div") + + #session + #view + #active + + #activeContent + + constructor() { + super() + this.intitialized = false + this.shadowRoot.append(this.#statusIndicator) + this.shadowRoot.append(this.#container) + this.#container.classList.add('container') + + this.#container.append(this.#navigation) + this.#container.append(this.#content) + this.#statusIndicator.classList.add("status-indicator") + + this.#navigation.addEventListener(ViewNavigation.MODE, this.binding(this.#onNavigationModeChange)) + this.#voiceEditor.addEventListener(VoiceEditor.SOLO, this.binding(this.#onSoloToggle)) + + watch(this, "session", this.binding(this.#onSessionChange)) + watch(this, "view", this.binding(this.#onViewChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(ViewEditor.style) + this.intitialized = true + } + + set session(value) { + this.#session = value + } + + get session() { + return this.#session + } + + set view(value) { + this.#view = value + } + + get view() { + return this.#view + } + + set active(value) { + this.#active = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get active() { + return this.#active + } + + #onSoloToggle(event) { + this.#session.voiceSolo(event.detail) + } + + #onNavigationModeChange(event) { + if (this.#navigation.mode === ViewNavigation.NAVIGATE) { + this.#container.append(this.#content) + } else { + this.#content.remove() + } + } + + #onSessionChange(signal) { + if (signal.path.length > 1) return + this.addToRenderQueue(this.binding(this.#update)) + } + + #onViewChange(signal) { + if (signal.path.length > 1) return + this.addToRenderQueue(this.binding(this.#update)) + } + + #update() { + if (!this.#session || !this.#view) return + this.#navigation.session = this.#session + this.#navigation.view = this.#view + + const validPath = this.#session.getValidSubpath(this.#view.path) + + let content + + if (this.#active) this.#statusIndicator.classList.add("active") + else this.#statusIndicator.classList.remove("active") + + if (validPath.length == 0) { + this.#settingsEditor.session = this.#session + content = this.#settingsEditor + } else if (validPath.length == 1) { + const id = validPath[0] + const channel = this.#session.findChannel(id) + this.#channelEditor.channel = channel + content = this.#channelEditor + } else if (validPath.length == 2) { + const channelId = validPath[0] + const channel = this.#session.findChannel(channelId) + const voiceId = validPath[1] + const voice = channel.findVoice(voiceId) + this.#voiceEditor.voice = voice + content = this.#voiceEditor + } else { + this.#oscillatorEditor.settings = this.#session.settings + this.#oscillatorEditor.last = validPath.slice(-1)[0] + this.#oscillatorEditor.parent = this.#session.getPathReference(validPath.slice(0,-1)) + this.#oscillatorEditor.reference = this.#session.getPathReference(validPath) + content = this.#oscillatorEditor + } + + if (content !== this.#activeContent) { + if (this.#activeContent) this.#activeContent.remove() + this.#activeContent = content + this.#content.append(this.#activeContent) + } + } + + destroy() { + unwatch(this, "session", this.binding(this.#onSessionChange)) + unwatch(this, "view", this.binding(this.#onViewChange)) + super.destroy() + } +} \ No newline at end of file diff --git a/dist/component/view-navigation.css b/dist/component/view-navigation.css new file mode 100644 index 0000000..96222b6 --- /dev/null +++ b/dist/component/view-navigation.css @@ -0,0 +1,25 @@ +:host { + user-select: none; + display: flex; + white-space: nowrap; + box-sizing: border-box; +} + +.container { + display: flex; + flex-direction: column; + gap: 6px; +} + +.container.force-row { + + flex-direction: row; + flex-wrap: wrap; +} + +.item-row { + display: flex; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} \ No newline at end of file diff --git a/dist/component/view-navigation.js b/dist/component/view-navigation.js new file mode 100644 index 0000000..5246dea --- /dev/null +++ b/dist/component/view-navigation.js @@ -0,0 +1,399 @@ +import clone from "../data/clone.js" +import updateUIList from "../data/update-ui-list.js" +import watch from "../glue/watch.js" +import Channel from "../model/channel.js" +import resetChannel from "../model/reset-channel.js" +import resetVoice from "../model/reset-voice.js" +import Session from "../model/session.js" +import Voice from "../model/voice.js" +import Component from "./component.js" +import Button from "./button.js" +import ButtonList from "./button-list.js" + +const INSERT_OSCILLATOR = "insert-oscillator" +const NAVIGATE = "navigate" + +export default class ViewNavigation extends Component { + + static CHANGE = 'change' + static MODE = 'mode' + static NAVIGATE ='navigate' + static INSERT_OSCILLATOR = "insert-oscillator" + static UP = 'up' + static style = 'component/view-navigation.css' + + #container = document.createElement('div') + #mode = NAVIGATE + #view + + #session + + constructor() { + super() + this.intitialized = false + this.#container.classList.add("container") + + this.#container.addEventListener(Button.UP, this.binding(this.#onButtonUp)) + watch(this, "session", this.binding(this.#onSessionChange)) + watch(this, "view", this.binding(this.#onViewChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(ViewNavigation.style) + this.intitialized = true + this.shadowRoot.append(this.#container) + this.addToRenderQueue(this.binding(this.#render)) + } + + #onButtonUp(e) { + e.stopPropagation() + const children = Array.from(this.#container.children) + + if (e.detail.action === "session") { + this.#view.path = [] + } + if (e.detail.action === "add-channel") { + this.#session.channels.push({}) + const channelId = this.#session.channels[this.#session.channels.length-1].id + this.#view.path = [channelId] + } + if (e.detail.action === "channel") { + this.#view.path = [e.detail.id] + } + if (e.detail.action === "add-voice") { + const channel = this.#session.findChannel(this.#view.path[0]) + channel.voices.push(clone(this.#session.defaults.voice, true)) + channel.voices[channel.voices.length-1].state = Voice.TRIGGER_ATTACK + const voiceId = channel.voices[channel.voices.length-1].id + this.#view.path = [this.#view.path[0], voiceId] + } + if (e.detail.action === "add-oscillator") { + const ref = this.#session.getPathReference(this.#view.path) + let empty = {} + if (e.detail.id === "fm") empty = clone(this.#session.defaults.fm, true) + else if (e.detail.id === "am") empty = clone(this.#session.defaults.am, true) + else if (e.detail.id === "em") empty = clone(this.#session.defaults.em, true) + else if (e.detail.id === "sx") empty = clone(this.#session.defaults.sx, true) + else if (e.detail.id === "gain") empty = clone(this.#session.defaults.gain, true) + else if (e.detail.id === "transpose") empty = clone(this.#session.defaults.transpose, true) + ref[e.detail.id] = empty + this.mode = NAVIGATE + this.#view.path.push(e.detail.id) + } + if (e.detail.action === "select-oscillator") { + this.mode = NAVIGATE + this.#view.path = e.detail.path + } + if (e.detail.action === "choose-oscillator") { + const ref = this.#session.getPathReference(this.#view.path) + this.mode = INSERT_OSCILLATOR + } + if (e.detail.action === "voice") { + this.mode = NAVIGATE + this.#view.path = [this.#view.path[0], e.detail.id] + } + if (e.detail.action === "toggle-collapse") { + this.mode = NAVIGATE + this.#view.navigationCollapsed = !this.#view.navigationCollapsed + } + if (e.detail.action === "delete-oscillator") { + + const ref = this.#session.getPathReference(this.#view.path.slice(0,-1)) + ref[e.detail.id] = null + this.#session.validateAllPaths() + } + if (e.detail.action === "duplicate-voice") { + const channel = this.#session.findChannel(this.#view.path[0]) + const voice = clone(channel.findVoice(this.#view.path[1]), true) + resetVoice(voice) + channel.voices.push(voice) + channel.voices[channel.voices.length-1].state = Voice.TRIGGER_ATTACK + const voiceId = channel.voices[channel.voices.length-1].id + this.#view.path = [this.#view.path[0], voiceId] + } + if (e.detail.action === "duplicate-channel") { + const channel = clone(this.#session.findChannel(this.#view.path[0]), true) + resetChannel(channel) + this.#session.channels.push(channel) + + const channelId = this.#session.channels[this.#session.channels.length-1].id + this.#view.path = [channelId] + } + if (e.detail.action === "delete-voice") { + + const channel = this.#session.findChannel(this.#view.path[0]) + const voice = channel.findVoice(this.#view.path[1]) + voice.state = Voice.TRIGGER_DELETE + + } + if (e.detail.action === "delete-channel") { + + const channel = this.#session.findChannel(this.#view.path[0]) + channel.state = Channel.TRIGGER_RELEASE + + } + this.dispatchEvent( + new CustomEvent( + ViewNavigation.UP, + { + detail: children.indexOf(e.detail), + bubbles: true, + composed: true + } + ) + ) + } + + set session(value) { + this.#session = value + } + + get session() { + return this.#session + } + + set view(value) { + this.#view = value + } + + get view() { + return this.#view + } + + set mode(value) { + this.#mode = value + this.dispatchEvent( new CustomEvent( + ViewNavigation.MODE, + { + detail: this.#mode, + composed: true + } + )) + this.addToRenderQueue(this.binding(this.#render)) + } + + get mode() { + return this.#mode + } + + set active(index) { + const children = Array.from(this.#container.children) + for(let i = 0; i < children.length; i++) { + children[i].active = (i == index) + } + } + + get active() { + const children = Array.from(this.#container.children) + for(let i = 0; i < children.length; i++) { + if (children[i].active) return i + } + return -1 + } + + #onSessionChange(signal) { + if (signal.path[0].property === "phase") return + this.addToRenderQueue(this.binding(this.#render)) + + } + + #onViewChange(signal) { + if (signal.path.length > 1) return + this.addToRenderQueue(this.binding(this.#render)) + } + + #getOscillatorFooter(oscillator) { + const f = [] + if (oscillator.am) f.push('A') + if (oscillator.fm) f.push('F') + if (oscillator.transpose) f.push('P') + if (oscillator.em) f.push('E') + if (oscillator.sx) f.push('S') + if (oscillator.gain) f.push('G') + return f.join("") + } + + #getOscillatorName(oscillator) { + switch (oscillator) { + case "am": + return "AM" + case "fm": + return "FM" + case "transpose": + return "Pitch" + case "em": + return "Exponent" + case "sx": + return "Scale" + case "gain": + default: + return "Gain" + } + } + + #getVoiceFooter(voice) { + return this.#getOscillatorFooter(voice.oscillator) + } + + #render() { + const rows = [] + const actionList = {items:[]} + if (this.#session && this.#view) { + + const showSiblings = this.#session.navigationMode === Session.SIBLINGS + const validPath = this.#session.getValidSubpath(this.#view.path) + + if (this.#view.navigationCollapsed) { + if (validPath.length == 0) { + actionList.items.push({header: "Session", footer: `${this.#session.channels.length}`, action: "toggle-collapse", label: this.#session.name, mode: "active", invisible: false, wrap: false}) + } else if (validPath.length == 1) { + let activeChannel = this.#session.findChannel(validPath[0]) + actionList.items.push({header: "Channel", footer: `${activeChannel.voices.length}`, action: "toggle-collapse", label: activeChannel.name, mode: "active", id: activeChannel.id, invisible: false, wrap: false}) + } else if (validPath.length == 2) { + let activeChannel = this.#session.findChannel(validPath[0]) + let activeVoice = activeChannel.findVoice(validPath[1]) + actionList.items.push({header: "Voice", footer: this.#getVoiceFooter(activeVoice), action: "toggle-collapse", label: activeVoice.name, mode: "active", id:activeVoice.id, invisible: false, wrap: false}) + } else if (validPath.length > 2) { + let ref = this.#session.getPathReference(validPath) + + let type = validPath[validPath.length-1].toUpperCase() + actionList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref), action: "toggle-collapse", label: type, mode: "active", id:validPath[validPath.length-1], invisible: false, wrap: false}) + } + } else { + if (this.#mode === NAVIGATE) { + let sessionList = {items:[]} + + // Session + if (validPath.length == 0) { + sessionList.items.push({header: "Session", mode: "active", footer: `${this.#session.channels.length}`, action: "toggle-collapse", label: this.#session.name, invisible: false, wrap: false}) + } else { + sessionList.items.push({header: "Session", mode: "path", footer: `${this.#session.channels.length}`, action: "session", label: this.#session.name, mode: "path", invisible: false, wrap: false}) + } + + // Channels + if (validPath.length == 0) { + this.#session.channels.forEach(channel=>{ + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "default", id: channel.id, invisible: false, wrap: false}) + }) + } else if (validPath.length == 1) { + this.#session.channels.forEach(channel=>{ + if (validPath[0] === channel.id) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "toggle-collapse", label: channel.name, mode: "active", id: channel.id, invisible: false, wrap: false}) + } else if (showSiblings) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "default", id: channel.id, invisible: false, wrap: false}) + } + }) + } else { + this.#session.channels.forEach(channel=>{ + if (validPath[0] === channel.id) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "path", id: channel.id, invisible: false, wrap: false}) + } else if (showSiblings) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "default", id: channel.id, invisible: false, wrap: false}) + + } + }) + } + if (sessionList.items.length) rows.push(sessionList) + + // Voices + let voiceList = {items:[]} + if (validPath.length >= 1) { + let activeChannel = this.#session.findChannel(validPath[0]) + activeChannel.voices.forEach(voice=>{ + if (validPath.length == 2 && validPath[1] === voice.id) { + voiceList.items.push({header: "Voice", footer: this.#getVoiceFooter(voice), action: "toggle-collapse", label: voice.name, mode: "active", id: voice.id, invisible: false, wrap: false}) + } else if (validPath.length > 2 && validPath[1] === voice.id) { + voiceList.items.push({header: "Voice", footer: this.#getVoiceFooter(voice), action: "voice", label: voice.name, mode: "path", id: voice.id, invisible: false, wrap: false}) + } else if (showSiblings || validPath.length == 1) { + voiceList.items.push({header: "Voice", footer: this.#getVoiceFooter(voice), action: "voice", label: voice.name, mode: "default", id: voice.id, invisible: false, wrap: false}) + } + }) + } + if (voiceList.items.length) rows.push(voiceList) + + // Oscillators + let oscillatorOrder = ["gain", "am", "fm", "transpose", "em", "sx"] + let oscillatorInsertPossible = false + if (validPath.length >= 2) { + let p = [] + + for (let i = 0; i < validPath.length; i++) { + p.push(validPath[i]) + const ref = this.#session.getPathReference(p) + if (i>=1) { + let oscillatorCount = 0 + let oscillatorList = {items:[]} + oscillatorOrder.forEach(name=>{ + const active = (i == validPath.length-2) && name === validPath[i+1] + const ispath = (i < validPath.length-2) && name === validPath[i+1] + if (ref[name]) { + oscillatorCount++ + const oscName = this.#getOscillatorName(name) + if (active) { + oscillatorList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref[name]), action: "toggle-collapse", label: oscName, mode: "active", path: [...p, name], invisible: false, wrap: false}) + } else if (ispath) { + oscillatorList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref[name]), action: "select-oscillator", label: oscName, mode: "path", id: name, path: [...p, name], invisible: false, wrap: false}) + } else if (showSiblings || i == validPath.length-1) { + oscillatorList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref[name]), action: "select-oscillator", label: oscName, mode: "default", id: name, path: [...p, name], invisible: false, wrap: false}) + } + } + + }) + if (oscillatorList.items.length != oscillatorOrder.length) oscillatorInsertPossible = true + if (oscillatorList.items.length) rows.push(oscillatorList) + } + } + + } + + // Actions + if (validPath.length == 0) { + actionList.items.push({header: "Channel", footer: "", action:"add-channel", label: "Add", mode: "insert", invisible: false, wrap: false}) + } else if (validPath.length == 1) { + let activeChannel = this.#session.findChannel(validPath[0]) + actionList.items.push({header: "Voice", footer: "", action:"add-voice", label: "Add", mode: "insert", invisible: false, wrap: false}) + actionList.items.push({header: "Channel", footer: activeChannel.name, action: "duplicate-channel", label: "Duplicate", mode: "insert", id: validPath[0], invisible: false, wrap: false}) + actionList.items.push({header: "Channel", footer: activeChannel.name, action: "delete-channel", label: "Delete", mode: "delete", id: validPath[0], invisible: false, wrap: false}) + } else if (validPath.length == 2) { + let activeChannel = this.#session.findChannel(validPath[0]) + let activeVoice + if (activeChannel) activeVoice = activeChannel.findVoice(validPath[1]) + if (oscillatorInsertPossible) actionList.items.push({header: "Oscillator", footer: "", action: "choose-oscillator", label: "Add", mode: "insert", invisible: false, wrap: false}) + actionList.items.push({header: "Voice", footer: activeVoice.name, action: "duplicate-voice", label: "Duplicate", mode: "insert", id: validPath[1], invisible: false, wrap: false}) + actionList.items.push({header: "Voice", footer: activeVoice.name, action: "delete-voice", label: "Delete", mode: "delete", id: validPath[1], invisible: false, wrap: false}) + } else if (validPath.length > 2) { + if (oscillatorInsertPossible) actionList.items.push({header: "Oscillator", footer: "", action: "choose-oscillator", label: "Add", mode: "insert", invisible: false, wrap: false}) + actionList.items.push({header: "Oscillator", footer: "", action: "delete-oscillator", label: "Delete", mode: "delete", id: validPath[validPath.length-1], invisible: false, wrap: false}) + } + } else if (this.#mode === INSERT_OSCILLATOR) { + let activeChannel = this.#session.findChannel(validPath[0]) + let activeVoice + if (activeChannel) activeVoice = activeChannel.findVoice(validPath[1]) + if (activeVoice) { + if (validPath.length == 2) actionList.items.push({header: "Oscillator", footer: "Cancel", action: "voice", label: "Cancel", mode: "active", id:activeVoice.id}) + else actionList.items.push({header: "Oscillator", footer: "Cancel", action: "select-oscillator", label: "Cancel", mode: "active", path: validPath}) + } + let ref = this.#session.getPathReference(validPath) + if (!ref.gain) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Gain", mode: "insert", id:"gain", path: [...validPath, "gain"]}) + if (!ref.am) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "AM", mode: "insert", id:"am", path: [...validPath, "am"]}) + if (!ref.fm) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "FM", mode: "insert", id:"fm", path: [...validPath, "fm"]}) + if (!ref.transpose) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Pitch", mode: "insert", id:"transpose", path: [...validPath, "transpose"]}) + if (!ref.em) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Exponent", mode: "insert", id:"em", path: [...validPath, "em"]}) + if (!ref.sx) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Scale", mode: "insert", id:"sx", path: [...validPath, "sx"]}) + + } + } + } + + if (actionList.items.length) rows.push(actionList) + + if (this.#session && this.#session.navigationMode === Session.COMPACT) this.#container.classList.add("force-row") + else this.#container.classList.remove("force-row") + updateUIList(this.#container, ButtonList, rows) + } + + destroy() { + super.destroy() + } +} \ No newline at end of file diff --git a/dist/component/voice-editor.css b/dist/component/voice-editor.css new file mode 100644 index 0000000..57d5ccd --- /dev/null +++ b/dist/component/voice-editor.css @@ -0,0 +1,32 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} + +.content { + display: flex; + flex-direction: column; +} + +.hidden { + display: none; +} + +.row { + max-width: 100%; + display: flex; + flex-direction: row; + flex-wrap: wrap; + +} +canvas { + display:flex; +} \ No newline at end of file diff --git a/dist/component/voice-editor.js b/dist/component/voice-editor.js new file mode 100644 index 0000000..e6ee5f4 --- /dev/null +++ b/dist/component/voice-editor.js @@ -0,0 +1,194 @@ + +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Component from "./component.js" +import WaveSplineEditor from "./wave-spline-editor.js" +import Voice from "../model/voice.js" +import RotaryGroup from "./rotary-group.js" +import TimeDriver from "./rotary-driver/time-driver.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import beautifyTime from "../music/beautify-time.js" +import Button from "./button.js" + +export default class VoiceEditor extends Component { + + static ZERO = 'zero' + static KILL = 'kill' + static CHANGE = 'change' + static SOLO = 'solo' + static style = 'component/voice-editor.css' + + #content = document.createElement('div') + + #waveSplineEditor = WaveSplineEditor.create() + + #stateToggle = Button.create() + #zeroButton = Button.create() + #soloToggle = Button.create() + #gainRotary = RotaryGroup.create() + #attackEditor = RotaryGroup.create() // RampEditor.create() + #releaseEditor = RotaryGroup.create()// RampEditor.create() + + #voice + + constructor() { + super() + this.intitialized = false + + this.#soloToggle.header = "Bus" + this.#soloToggle.mode = "toggle" + this.shadowRoot.append(this.#soloToggle) + this.#soloToggle.addEventListener(Button.UP, this.binding(this.#onSoloToggle)) + + this.#stateToggle.header = "State" + this.#stateToggle.mode = "toggle" + this.shadowRoot.append(this.#stateToggle) + this.#stateToggle.addEventListener(Button.UP, this.binding(this.#onStateToggle)) + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + this.#gainRotary.drivers = [ + new GainDriver({name: "Gain"}) + ] + this.shadowRoot.append(this.#gainRotary) + this.#gainRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGainChange)) + + this.#attackEditor.drivers = [ + new TimeDriver({name: "Attack"}) + ] + this.shadowRoot.append(this.#attackEditor) + this.#attackEditor.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onAttackChange)) + + this.#releaseEditor.header = "Release" + this.#releaseEditor.drivers = [ + new TimeDriver({name: "Release"}) + ] + + this.#releaseEditor.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onReleaseChange)) + this.shadowRoot.append(this.#releaseEditor) + + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + this.shadowRoot.append(this.#waveSplineEditor) + watch(this, "voice", this.binding(this.#onVoiceChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(VoiceEditor.style) + this.intitialized = true + this.#update() + this.#updateTime() + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + VoiceEditor.ZERO, + { + composed: true, + detail: this.#voice.id + } + ) + ) + } + + #onGainChange(e) { + this.#voice.gain = this.#gainRotary.value + } + + #onAttackChange(e) { + this.#voice.attack = this.#attackEditor.value + } + + #onReleaseChange(e) { + this.#voice.release = this.#releaseEditor.value + + } + + #onSoloToggle(e) { + this.dispatchEvent( + new CustomEvent( + VoiceEditor.SOLO, + { + detail: this.#voice.id, + composed: true + } + ) + ) + } + + #onStateToggle(e) { + if ( + this.#voice.state === Voice.ATTACK + || this.#voice.state === Voice.SUSTAIN + ) { + this.#voice.state = Voice.TRIGGER_RELEASE + } else if ( + this.#voice.state === Voice.RELEASE + || this.#voice.state === Voice.IDLE + ) { + this.#voice.state = Voice.TRIGGER_ATTACK + } + } + + get voice() { + return this.#voice + } + + set voice(value) { + this.#voice = value + } + + set settings(value) { + this.#waveSplineEditor.settings = value + } + + #onVoiceChange(signal) { + if (signal.path[0].property === "phase") return + if (signal.path.length == 1) this.#update() + if (signal.path.length >= 2) this.#updateTime() + + } + + #updateTime() { + const time = beautifyTime(this.#voice.oscillator.length * this.#voice.oscillator.wave.viewZoom) + this.#waveSplineEditor.maxXLabel = `${time.value} ${time.unit}` + } + + #update() { + if (this.#voice) { + if (this.#voice.bus === "solo") { + this.#soloToggle.label = "solo" + this.#soloToggle.mode = "solo" + } else { + this.#soloToggle.label = "mix" + this.#soloToggle.mode = "toggle" + } + this.#stateToggle.label = this.#voice.state + //this.#oscillatorEditor.path = this.#voice.path + this.#waveSplineEditor.waveSplineOscillator = this.#voice.oscillator + + this.#gainRotary.value = this.#voice.gain + this.#attackEditor.value = this.#voice.attack + this.#releaseEditor.value = this.#voice.release + this.#content.classList.remove("hidden") + } else { + this.#content.classList.add("hidden") + } + } + + destroy() { + unwatch(this, "voice") + this.#waveSplineEditor.destroy() + this.#attackEditor.destroy() + this.#releaseEditor.destroy() + super.destroy() + } + +} \ No newline at end of file diff --git a/dist/component/wave-spline-editor.css b/dist/component/wave-spline-editor.css new file mode 100644 index 0000000..f4ef18d --- /dev/null +++ b/dist/component/wave-spline-editor.css @@ -0,0 +1,29 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + max-width: 100%; + gap: 6px; +} + +.settings-container { + flex-direction: row; + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.wave-spline-container { + height: 72px; + flex: 1; +} + + +canvas { + display:flex; +} \ No newline at end of file diff --git a/dist/component/wave-spline-editor.js b/dist/component/wave-spline-editor.js new file mode 100644 index 0000000..3c74d4f --- /dev/null +++ b/dist/component/wave-spline-editor.js @@ -0,0 +1,308 @@ +import watch from "../glue/watch.js" +import Component from "./component.js" +import Button from "./button.js" +import BarDriver from "./rotary-driver/bar-driver.js" +import ExponentDriver from "./rotary-driver/exponent-driver.js" +import FractionDriver from "./rotary-driver/fraction-driver.js" +import FrequencyDriver from "./rotary-driver/frequency-driver.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import GridDriver from "./rotary-driver/grid-driver.js" +import NoteDriver from "./rotary-driver/note-driver.js" +import QuantizeDriver from "./rotary-driver/quantize-driver.js" +import TimeDriver from "./rotary-driver/time-driver.js" +import RotaryGroup from "./rotary-group.js" +import WaveSplineGraph from "./wave-spline-graph.js" + +export default class WaveSplineEditor extends Component { + + static CHANGE = 'change' + static style = 'component/wave-spline-editor.css' + + #waveSplineOscillator + #waveSplineGraph = WaveSplineGraph.create() + + #container = document.createElement('div') + #viewContainer = document.createElement('div') + #waveSplineContainer = document.createElement('div') + #tempoLock = Button.create() + #frequency = RotaryGroup.create() + #exponentRotary = RotaryGroup.create() + #phaseShiftRotary = RotaryGroup.create() + #transformCenterRotary = RotaryGroup.create() + #transformRangeRotary = RotaryGroup.create() + #viewZoomRotary = RotaryGroup.create() + #viewPositionRotary = RotaryGroup.create() + #quantizeXRotary = RotaryGroup.create() + #quantizeYRotary = RotaryGroup.create() + #gridXRotary = RotaryGroup.create() + #gridYRotary = RotaryGroup.create() + #settings + + #frequencyFractionDriver = new FractionDriver() + #frequencyBarDriver = new BarDriver() + + constructor() { + super() + this.intitialized = false + this.#frequency.drivers = [ + new FrequencyDriver(), + new NoteDriver(), + new TimeDriver(), + this.#frequencyFractionDriver, + this.#frequencyBarDriver + ] + + this.#exponentRotary.drivers = [ + new ExponentDriver() + ] + this.#phaseShiftRotary.drivers = [ + new GainDriver({name: "Phase offset"}) + ] + this.#viewZoomRotary.drivers = [ + new GainDriver({name: "View Zoom"}) + ] + this.#viewPositionRotary.drivers = [ + new GainDriver({name: "View Position"}) + ] + + this.#transformCenterRotary.drivers = [ + new GainDriver({name:"Scale Center"}) + ] + this.#transformRangeRotary.drivers = [ + new GainDriver({name:"Scale Range"}) + ] + this.#gridXRotary.drivers = [ + new GridDriver({name:"Horizontal Grid"}) + ] + this.#gridYRotary.drivers = [ + new GridDriver({name:"Vertical Grid"}) + ] + this.#quantizeXRotary.drivers = [ + new QuantizeDriver({name:"Quantize Time"}) + ] + this.#quantizeYRotary.drivers = [ + new QuantizeDriver({name:"Quantize Amplitude"}) + ] + + this.#viewContainer.classList.add("settings-container") + this.#viewContainer.append(this.#viewZoomRotary) + this.#viewContainer.append(this.#viewPositionRotary) + this.#viewContainer.append(this.#gridXRotary) + this.#viewContainer.append(this.#gridYRotary) + this.shadowRoot.append(this.#viewContainer) + + this.#waveSplineContainer.classList.add("wave-spline-container") + this.#waveSplineContainer.append(this.#waveSplineGraph) + this.shadowRoot.append(this.#waveSplineContainer) + + this.#container.classList.add("settings-container") + this.shadowRoot.append(this.#container) + + this.#tempoLock.header = "Tempo" + this.#tempoLock.label = "Sync" + this.#tempoLock.footer = "" + this.#tempoLock.mode = "toggle" + this.#tempoLock.addEventListener(Button.UP, this.binding(this.#onTempoLockClick)) + this.#container.append(this.#tempoLock) + + this.#container.append(this.#frequency) + + this.#container.append(this.#exponentRotary) + this.#container.append(this.#transformCenterRotary) + this.#container.append(this.#transformRangeRotary) + + this.#container.append(this.#phaseShiftRotary) + + this.#container.append(this.#quantizeXRotary) + this.#container.append(this.#quantizeYRotary) + + this.#frequency.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onFrequencyChange)) + this.#frequency.addEventListener(RotaryGroup.DRIVER_CHANGE, this.binding(this.#onFrequencyDriverChange)) + + this.#transformCenterRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onTransformCenterChange)) + this.#transformRangeRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onTransformRangeChange)) + + this.#exponentRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onExponentRotaryChange)) + this.#phaseShiftRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onPhaseShiftChange)) + this.#viewZoomRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onViewZoomChange)) + this.#viewPositionRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onViewPositionChange)) + this.#quantizeXRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onQuantizeXRotaryChange)) + this.#quantizeYRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onQuantizeYRotaryChange)) + this.#gridXRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGridXRotaryChange)) + this.#gridYRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGridYRotaryChange)) + watch(this, "waveSplineOscillator", this.binding(this.#onWaveSplineOscillatorChange)) + watch(this, "settings", this.binding(this.#onSettingsChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(WaveSplineEditor.style) + this.intitialized = true + } + + #onTempoLockClick(e) { + this.#waveSplineOscillator.tempoSync = !this.#waveSplineOscillator.tempoSync + } + + #onFrequencyChange(e) { + this.#waveSplineOscillator.length = this.#frequency.value + } + + #onTransformCenterChange(e) { + this.#waveSplineOscillator.wave.transformCenter.x = this.#transformCenterRotary.value + } + + #onTransformRangeChange(e) { + this.#waveSplineOscillator.wave.transformRange.x = this.#transformRangeRotary.value + } + + #onPhaseShiftChange(e) { + this.#waveSplineOscillator.phaseShift = this.#phaseShiftRotary.value + } + + #onViewZoomChange(e) { + this.#waveSplineOscillator.wave.viewZoom = this.#viewZoomRotary.value + } + + #onViewPositionChange(e) { + this.#waveSplineOscillator.wave.viewPosition = this.#viewPositionRotary.value + } + + #onFrequencyDriverChange(e) { + this.#waveSplineOscillator.lengthDriver = this.#frequency.driver + } + + #onExponentRotaryChange(e) { + this.#waveSplineOscillator.wave.e = this.#exponentRotary.value + } + + #onQuantizeXRotaryChange(e) { + this.#waveSplineOscillator.wave.quantizeX = this.#quantizeXRotary.value + } + + #onQuantizeYRotaryChange(e) { + this.#waveSplineOscillator.wave.quantizeY = this.#quantizeYRotary.value + } + + #onGridXRotaryChange(e) { + this.#waveSplineOscillator.wave.gridX = this.#gridXRotary.value + } + + #onGridYRotaryChange(e) { + this.#waveSplineOscillator.wave.gridY = this.#gridYRotary.value + } + + set zero(value) { + this.#waveSplineGraph.zero = value + } + + get zero() { + return this.#waveSplineGraph.zero + } + + set minYLabel(value) { + this.#waveSplineGraph.minYLabel = value + } + + get minYLabel() { + return this.#waveSplineGraph.minYLabel + } + + set maxYLabel(value) { + this.#waveSplineGraph.maxYLabel = value + } + + get maxYLabel() { + return this.#waveSplineGraph.maxYLabel + } + + set maxXLabel(value) { + this.#waveSplineGraph.maxXLabel = value + } + + get maxXLabel() { + return this.#waveSplineGraph.maxXLabel + } + + set waveSplineOscillator(value) { + this.#waveSplineOscillator = value + } + + get waveSplineOscillator() { + return this.#waveSplineOscillator + } + + set settings(value) { + this.#settings = value + } + + get settings() { + return this.#settings + } + + #onSettingsChange(signal) { + this.#frequencyBarDriver.tempo = this.#settings.tempo + this.#frequencyFractionDriver.tempo = this.#settings.tempo + this.#update() + } + + #onWaveSplineOscillatorChange(signal) { + if (signal.path[0].property === "phase") this.#updatePlayhead() + else this.#update() + } + + #updatePlayhead() { + + if (this.#waveSplineOscillator.length > 0.5 ) { + this.#waveSplineGraph.playhead = (this.#waveSplineOscillator.phase + this.#waveSplineOscillator.phaseShift) % 1 + } else { + this.#waveSplineGraph.playhead = -1 + } + + } + + #update() { + if (this.#waveSplineOscillator && this.#waveSplineOscillator.wave) { + + this.#tempoLock.label = this.#waveSplineOscillator.tempoSync ? "Sync":"Free" + + this.#frequency.value = this.#waveSplineOscillator.length + this.#frequency.driver = this.#waveSplineOscillator.lengthDriver + this.#waveSplineGraph.waveSpline = this.#waveSplineOscillator.wave + this.#exponentRotary.value = this.#waveSplineOscillator.wave.e + this.#phaseShiftRotary.value = this.#waveSplineOscillator.phaseShift + this.#viewZoomRotary.value = this.#waveSplineOscillator.wave.viewZoom + + this.#viewPositionRotary.value = this.#waveSplineOscillator.wave.viewPosition + this.#transformCenterRotary.value = this.#waveSplineOscillator.wave.transformCenter.x + this.#transformRangeRotary.value = this.#waveSplineOscillator.wave.transformRange.x + this.#quantizeXRotary.value = this.#waveSplineOscillator.wave.quantizeX + this.#quantizeYRotary.value = this.#waveSplineOscillator.wave.quantizeY + this.#gridXRotary.value = this.#waveSplineOscillator.wave.gridX + this.#gridYRotary.value = this.#waveSplineOscillator.wave.gridY + + this.addToRenderQueue(this.binding(this.#updateDOM)) + } + + } + #updateDOM() { + if (this.#waveSplineOscillator.wave.viewZoom == 1 && this.#viewPositionRotary.parentElement) { + this.#viewPositionRotary.remove() + } else if (this.#waveSplineOscillator.wave.viewZoom != 1 && !this.#viewPositionRotary.parentElement) { + this.#viewContainer.insertBefore(this.#viewPositionRotary,this.#gridXRotary) + } + + if (!this.#waveSplineOscillator.sx && this.#transformCenterRotary.parentElement) { + this.#transformCenterRotary.remove() + } else if (this.#waveSplineOscillator.sx && !this.#transformCenterRotary.parentElement) { + this.#container.insertBefore(this.#transformCenterRotary, this.#quantizeXRotary) + } + + if (!this.#waveSplineOscillator.sx && this.#transformRangeRotary.parentElement) { + this.#transformRangeRotary.remove() + } else if (this.#waveSplineOscillator.sx && !this.#transformRangeRotary.parentElement) { + this.#container.insertBefore(this.#transformRangeRotary, this.#quantizeXRotary) + } + + } +} \ No newline at end of file diff --git a/dist/component/wave-spline-graph.css b/dist/component/wave-spline-graph.css new file mode 100644 index 0000000..0b0306d --- /dev/null +++ b/dist/component/wave-spline-graph.css @@ -0,0 +1,41 @@ +:host { + font-family: sans-serif; + user-select: none; + display: flex; + min-width: 72px; + min-height: 228px; + padding-top: 6px; + padding-bottom: 6px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + cursor: pointer; +} +canvas { + display:flex; + height: 204px; + touch-action: none; +} + +.header { + display: flex; + font-size: 9px; + margin-left: 6px; + margin-right: 6px; + min-height: 12px; + color: rgb(128,128,128); + flex-direction: row; + justify-content: space-between; +} + +.footer { + display: flex; + font-size: 9px; + margin-left: 6px; + margin-right: 6px; + min-height: 12px; + color: rgb(128,128,128); + flex-direction: row; + justify-content: space-between; +} diff --git a/dist/component/wave-spline-graph.js b/dist/component/wave-spline-graph.js new file mode 100644 index 0000000..89ed97e --- /dev/null +++ b/dist/component/wave-spline-graph.js @@ -0,0 +1,597 @@ + +import hslToRgb from "../color/hsl-to-rgb.js" +import rgbaToCss from "../color/rgba-to-css.js" +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import calculateDistance from "../math/calculate-distance.js" +import normalize from "../math/normalize.js" +import quantize from "../math/quantize.js" +import Point from "../model/point.js" +import findClosest from "../wave-spline/find-closest.js" +import solveWaveSpline from "../wave-spline/solve-wave-spline.js" +import Component from "./component.js" + +export default class WaveSplineGraph extends Component { + + static CHANGE = 'change' + static style = 'component/wave-spline-graph.css' + + #canvas = document.createElement('canvas') + #ctx + + #waveSpline// = new WaveSpline() + #horizontalPadding = 6 + #verticalPadding = 6 + #width + #height + #deepColor = hslToRgb({h: 0, s: 0, l: .25}) + #handleColor = hslToRgb({h: 0, s: 0, l: 1}) + #lineWidth = 2 + #gridWidth = 1 + #handleRadius = 3 + #zero = 0.5 + #minYLabel = "0" + #maxYLabel = "1" + #maxXLabel = "1" + #playhead = 0 + + #deleteThreshold = 20 + #selectionThreshold = 60 + #doubleTapDelay = 250 + #doubleTapDistance = 15 + + #lastTap = 0 + #lastTapPosition = new Point() + + #last = new Point() + + #selection = [] + + #innerWidth + #innerHeight + #top + #left + + #isDown + + #headerEl = document.createElement('div') + #maxXLabelEl = document.createElement('div') + #minYLabelEl = document.createElement('div') + #maxYLabelEl = document.createElement('div') + #footerEl = document.createElement('div') + + constructor() { + super() + this.intitialized = false + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 60) + this.#canvas.setAttribute("height", 60) + this.#ctx = this.#canvas.getContext("2d") + + this.observe(this.#canvas) + + this.#maxYLabelEl.classList.add("max-y") + this.#headerEl.append(this.#maxYLabelEl) + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.shadowRoot.append(this.#canvas) + + this.#minYLabelEl.classList.add("min-y") + this.#footerEl.append(this.#minYLabelEl) + + this.#maxXLabelEl.classList.add("max-x") + this.#footerEl.append(this.#maxXLabelEl) + + this.#footerEl.classList.add("footer") + this.shadowRoot.append(this.#footerEl) + + watch(this, "waveSpline", this.binding(this.#onWaveSplineChange)) + + this.#canvas.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.#canvas.addEventListener("pointercancel", this.binding(this.#onPointerCancel)) + this.#canvas.addEventListener("lostpointercapture", this.binding(this.#onPointerLost)) + + this.#updateValues() + this.#init() + } + + async #init() { + await this.appendStyleLink(WaveSplineGraph.style) + this.#calculate() + this.intitialized = true + } + + resize(contentRect) { + super.resize(contentRect) + this.#width = contentRect.width + this.#height = contentRect.height + this.#calculate() + } + + #onPointerDown(e) { + if (this.#isDown) return + if (e.button != 0) return + const now = Date.now() + if ( + now - this.#lastTap < this.#doubleTapDelay + && calculateDistance(this.#lastTapPosition, {x: e.clientX, y: e.clientY}) < this.#doubleTapDistance + ) { + this.#lastTap = 0 + this.#lastTapPosition.x = 0 + this.#lastTapPosition.y = 0 + this.#insertOrDelete(e) + } else { + this.#isDown = e.pointerId + this.#lastTap = Date.now() + this.#lastTapPosition.x = e.clientX + this.#lastTapPosition.y = e.clientY + this.#selectClosest(e) + if (this.#selection.length) { + this.#canvas.setPointerCapture(e.pointerId) + this.addEventListener("pointermove", this.binding(this.#onPointerMove)) + } + } + this.#last.x = e.clientX + this.#last.y = e.clientY + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#canvas.releasePointerCapture(e.pointerId) + this.#positionFromEvent(e) + this.#endDrag(e) + } + + #onPointerCancel(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#canvas.releasePointerCapture(e.pointerId) + this.#endDrag(e) + } + + #onPointerLost(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#canvas.releasePointerCapture(e.pointerId) + this.#endDrag(e) + } + + #onPointerMove(e) { + if (this.#isDown !== e.pointerId) return + this.#positionFromEvent(e) + } + + #endDrag(e) { + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + if(calculateDistance(this.#lastTapPosition, {x: e.clientX, y: e.clientY}) > 0) { + this.#alignToGrid(this.#selection) + } + } + + #waveSplineToDiagram(point) { + let from = Math.max(0, Math.min(1, this.#waveSpline.viewPosition * (1-this.#waveSpline.viewZoom))) + let range = this.#waveSpline.viewZoom + let to = from + range + return { + x: this.#innerWidth * ((point.x - from) / range), + y: this.#innerHeight * (1-point.y) + } + } + + #eventToWaveSpline(e) { + const p = this.#eventToDiagram(e) + + let from = Math.max(0, Math.min(1, this.#waveSpline.viewPosition * (1-this.#waveSpline.viewZoom))) + let range = this.#waveSpline.viewZoom + p.x = from + (p.x / this.#innerWidth) * range + p.y /= this.#innerHeight + p.y = 1-p.y + return p + } + + #eventToDiagram(e) { + const p = this.#eventToCanvas(e) + p.x -= this.#left + p.y -= this.#top + return p + } + + #eventToCanvas(e) { + const rect = this.#canvas.getBoundingClientRect() + return { + x: e.clientX - rect.left, + y: e.clientY - rect.top + } + } + + #insertOrDelete(e) { + const closest = this.#findClosest(e) + let insert = true + const dposition = this.#eventToDiagram(e) + if (closest) { + const point = this.#waveSplineToDiagram(closest) + const dist = calculateDistance(point, dposition) + if (dist < this.#deleteThreshold) { + insert = false + } + } + if (insert) { + const wposition = this.#alignPoint(this.#eventToWaveSpline(e)) + this.#waveSpline.points.push(wposition) + this.#waveSpline.sort() + } else if (closest) { + this.#waveSpline.points.splice(this.#waveSpline.points.indexOf(closest), 1) + } + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + } + + #findClosest(e) { + const wposition = this.#eventToWaveSpline(e) + return findClosest(wposition, this.#waveSpline.points, {x: this.#innerWidth / this.#waveSpline.viewZoom, y: this.#innerHeight}) + } + + #selectClosest(e) { + const closest = this.#findClosest(e) + let selected + if (closest) { + const distance = calculateDistance(this.#waveSplineToDiagram(closest), this.#eventToDiagram(e)) + if (distance < this.#selectionThreshold) { + selected = closest + } + + } + if (selected) this.#selection = [selected] + else this.#selection = [] + + } + + #alignPoint(point) { + point.x = quantize(point.x, this.#waveSpline.gridX, this.#waveSpline.gridXThreshold) + point.y = quantize(point.y, this.#waveSpline.gridY, this.#waveSpline.gridYThreshold) + return point + } + + + #alignToGrid(points) { + + points.forEach(point=>this.#alignPoint(point)) + this.#waveSpline.sort() + + } + + #positionFromEvent(e) { + let range = this.#waveSpline.viewZoom + + const dx = (e.clientX - this.#last.x) / (this.#innerWidth / range) + const dy = (e.clientY - this.#last.y) / -this.#innerHeight + + this.#last.x = e.clientX + this.#last.y = e.clientY + + this.#selection.forEach((point) => { + point.x = (point.x + dx + 1) % 1 + point.y = Math.min(1, Math.max(0, point.y + dy)) + }) + + this.#waveSpline.sort() + + this.dispatchEvent( + new CustomEvent( + WaveSplineGraph.CHANGE, + { + composed: true + } + ) + ) + } + + set playhead(value) { + if (this.#playhead === value) return + this.#playhead = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get playhead() { + return this.#playhead + } + + set zero(value) { + this.#zero = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get zero() { + return this.#zero + } + + set maxYLabel(value) { + this.#maxYLabel = value + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get maxYLabel() { + return this.#maxYLabel + } + + set minYLabel(value) { + this.#minYLabel = value + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get minYLabel() { + return this.#minYLabel + } + + set maxXLabel(value) { + this.#maxXLabel = value + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get maxXLabel() { + return this.#maxXLabel + } + + set waveSpline(value) { + this.#waveSpline = value + } + + get waveSpline() { + return this.#waveSpline + } + + #onWaveSplineChange(signal) { + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #calculate() { + this.#innerWidth = this.#width - this.#horizontalPadding * 2 + this.#innerHeight = this.#height - this.#verticalPadding * 2 + this.#top = this.#verticalPadding + this.#left = this.#horizontalPadding + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #updateValues() { + this.#maxYLabelEl.textContent = this.#maxYLabel + this.#minYLabelEl.textContent = this.#minYLabel + this.#maxXLabelEl.textContent = this.#maxXLabel + } + + + #renderCanvas() { + if (this.#canvas.width != this.#width) this.#canvas.width = this.#width + if (this.#canvas.height != this.#height) this.#canvas.height = this.#height + + let oversampling = 2 + let p + + let from = Math.max(0, Math.min(1, this.#waveSpline.viewPosition * (1-this.#waveSpline.viewZoom))) + let range = this.#waveSpline.viewZoom + let to = from + range + + const wo = this.#innerWidth * oversampling + this.#ctx.clearRect(0, 0, this.#width, this.#height) + + + // zero + { + this.#ctx.save() + this.#ctx.strokeStyle = "#909090" + this.#ctx.lineWidth = this.#lineWidth/2 + const y = Math.round(this.#top + this.#innerHeight * (1-this.#zero)) + this.#ctx.beginPath() + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left + this.#innerWidth, y) + this.#ctx.stroke() + this.#ctx.restore() + + } + + // min + if (this.#zero > 0) { + this.#ctx.save() + this.#ctx.strokeStyle = "#303030" + this.#ctx.lineWidth = this.#lineWidth/2 + const y = this.#top + this.#innerHeight + this.#ctx.beginPath() + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left + this.#innerWidth, y) + this.#ctx.stroke() + this.#ctx.restore() + + } + + // max + if (this.#zero < 1) { + this.#ctx.save() + this.#ctx.strokeStyle = "#303030" + this.#ctx.lineWidth = this.#lineWidth/2 + const y = this.#top + this.#ctx.beginPath() + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left + this.#innerWidth, y) + this.#ctx.stroke() + this.#ctx.restore() + + } + + if (!this.#waveSpline) return + + this.#ctx.save() + + // horizontal grid + if ( + this.#waveSpline.gridX < Number.MAX_SAFE_INTEGER + ) { + const it = this.#innerWidth / this.#waveSpline.gridX / this.#waveSpline.viewZoom + for (let i = 0; i <= this.#waveSpline.gridX; i++) { + const x = Math.round( + this.#left + i * it - from * this.#innerWidth / this.#waveSpline.viewZoom + ) + if (x >= this.#left && x <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = "#303030" // rgbaToCss(this.#deepColor) + this.#ctx.lineWidth = this.#gridWidth + this.#ctx.moveTo(x, this.#top) + this.#ctx.lineTo(x, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + } + } + + // vertical grid + if ( + this.#waveSpline.gridY < Number.MAX_SAFE_INTEGER + ) { + const it = this.#innerHeight / this.#waveSpline.gridY + for (let i = 0; i <= this.#waveSpline.gridY; i++) { + const y = Math.round(this.#top + i * it) + this.#ctx.beginPath() + this.#ctx.strokeStyle = "#303030" // rgbaToCss(this.#deepColor) + this.#ctx.lineWidth = this.#gridWidth + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left+this.#innerWidth, y) + this.#ctx.stroke() + } + } + + // Transform range + this.#ctx.save() + const leftRange = Math.max( + this.#left, + this.#left + (this.#waveSpline.transformCenter.x - this.#waveSpline.transformRange.x) * this.#innerWidth/range + ) + if (leftRange >= this.#left && leftRange <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#003477' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.setLineDash([2,4]); + this.#ctx.moveTo(leftRange, this.#top) + this.#ctx.lineTo(leftRange, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + const rightRange = Math.min( + this.#left + this.#innerWidth, + this.#left + (this.#waveSpline.transformCenter.x + this.#waveSpline.transformRange.x) * this.#innerWidth/range + ) + if (rightRange >= this.#left && rightRange <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#003477' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.setLineDash([2,4]); + this.#ctx.moveTo(rightRange, this.#top) + this.#ctx.lineTo(rightRange, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + this.#ctx.restore() + + // Transform center + this.#ctx.save() + const scaleCenter = Math.max( + this.#left, + Math.min( + this.#left + this.#innerWidth, + this.#left + this.#waveSpline.transformCenter.x * this.#innerWidth/range + ) + ) + + if (scaleCenter >= this.#left && scaleCenter <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#003477' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.setLineDash([4,2]); + this.#ctx.moveTo(scaleCenter, this.#top) + this.#ctx.lineTo(scaleCenter, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + this.#ctx.restore() + + // quantized Wavespline + if ( + !this.#waveSpline.quantizeX < Number.MAX_SAFE_INTEGER || + !this.#waveSpline.quantizeY < Number.MAX_SAFE_INTEGER + ) { + // render quantized no oversampling + for (let x = 0; x < this.#innerWidth; x++) { + const px = x / this.#innerWidth + + let t = normalize(px, {min: from, max:to}) + + let y = solveWaveSpline(this.#waveSpline, t%1) + let c = {x: this.#left + x, y: y} + c.y = this.#top + normalize((1-c.y ), {max: this.#innerHeight}) + if (p) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = rgbaToCss(this.#deepColor) + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.moveTo(p.x, p.y) + this.#ctx.lineTo(c.x, c.y) + this.#ctx.stroke() + } + p = c + } + } + p = null + + // Wavespline + for (let x = 0; x < wo; x++) { + const px = x / wo + let t = normalize(px, {min: from, max:to}) + let y = solveWaveSpline(this.#waveSpline, t%1, 1, 1, 1, true) + let c = {x: this.#left + x / oversampling, y: y} + c.y = this.#top + normalize((1-c.y ), {max: this.#innerHeight}) + if (p) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = rgbaToCss(this.#handleColor) + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.moveTo(p.x, p.y) + this.#ctx.lineTo(c.x, c.y) + this.#ctx.stroke() + } + p = c + + } + this.#ctx.restore() + + // playhead + this.#ctx.save() + const playheadPos = this.#left + this.#playhead * this.#innerWidth/range + if (playheadPos >= this.#left && playheadPos <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#cc0000' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.moveTo(playheadPos, this.#top) + this.#ctx.lineTo(playheadPos, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + this.#ctx.restore() + + // wavespline points + for (let i = 0; i < this.#waveSpline.points.length; i++) { + let s = this.#waveSpline.points[i] + let x = this.#left + (s.x - from) * this.#innerWidth/range + if (x >= this.#left && x <= this.#left+this.#innerWidth) { + this.#ctx.save() + this.#ctx.beginPath(); + this.#ctx.fillStyle = rgbaToCss(this.#handleColor) + this.#ctx.arc(x , this.#top + (1-s.y) * this.#innerHeight, this.#handleRadius, 0, 2 * Math.PI) + this.#ctx.fill() + this.#ctx.restore() + } + } + } + + destroy() { + unwatch(this) + this.#waveSpline = null + this.#canvas.removeEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + this.#canvas.removeEventListener("pointerup", this.binding(this.#onPointerUp)) + super.destroy() + } +} \ No newline at end of file diff --git a/dist/data/clone.js b/dist/data/clone.js new file mode 100644 index 0000000..c9c015b --- /dev/null +++ b/dist/data/clone.js @@ -0,0 +1,18 @@ +export default function clone(obj, anonymize = false) { + obj = JSON.parse(JSON.stringify(obj)) + if (anonymize) removeIds(obj) + return obj +} + +function removeIds(obj) { + if (!obj) return + if (Array.isArray(obj)) { + obj.forEach(removeIds) + } else if (typeof obj === "object") { + if (obj.id) delete obj.id + if (obj.name) delete obj.name + Object.values(obj).forEach(removeIds) + } + return obj + +} \ No newline at end of file diff --git a/dist/data/generate-id.js b/dist/data/generate-id.js new file mode 100644 index 0000000..5969281 --- /dev/null +++ b/dist/data/generate-id.js @@ -0,0 +1,8 @@ +import generateUuidV4 from "./generate-uuid-v4.js" + +export default function generateId() { + // when crypto available + if (typeof crypto !== "undefined") return crypto.randomUUID() + // otherwise (Audio worklets seem to not support it) + return generateUuidV4() +} \ No newline at end of file diff --git a/dist/data/generate-uuid-v4.js b/dist/data/generate-uuid-v4.js new file mode 100644 index 0000000..c9f2473 --- /dev/null +++ b/dist/data/generate-uuid-v4.js @@ -0,0 +1,6 @@ +export default function generateUuidV4() { + return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, (c) => { + const r = Math.floor(Math.random() * 16) + return r.toString(16) + }); +} \ No newline at end of file diff --git a/dist/data/get-properties.js b/dist/data/get-properties.js new file mode 100644 index 0000000..daf088f --- /dev/null +++ b/dist/data/get-properties.js @@ -0,0 +1,9 @@ +export default function getProperties(instance, limit = Object) { + let properties = {} + const proto = Object.getPrototypeOf(instance) + Object.assign(properties, Object.getOwnPropertyDescriptors(proto)) + if (proto !== limit.prototype) { + return Object.assign(properties, getProperties(proto, limit)) + } + return properties +} \ No newline at end of file diff --git a/dist/data/instance-from.js b/dist/data/instance-from.js new file mode 100644 index 0000000..32d40e5 --- /dev/null +++ b/dist/data/instance-from.js @@ -0,0 +1,5 @@ +export default function instanceFrom(cls, object) { + if (!object) return null + if (object instanceof cls) return object + return new cls(object) +} \ No newline at end of file diff --git a/dist/data/make-enumerable.js b/dist/data/make-enumerable.js new file mode 100644 index 0000000..d8f6ddb --- /dev/null +++ b/dist/data/make-enumerable.js @@ -0,0 +1,11 @@ +import getProperties from "./get-properties.js"; + +export default function makeEnumerable(instance, cls) { + const properties = getProperties(instance, cls) + for (const descriptor in properties) { + if (properties[descriptor].get && properties[descriptor].set) { + properties[descriptor].enumerable = true + Object.defineProperty(instance, descriptor, {...properties[descriptor], enumerable: true}); + } + } +} \ No newline at end of file diff --git a/dist/data/manage-typed-array.js b/dist/data/manage-typed-array.js new file mode 100644 index 0000000..1f8e2df --- /dev/null +++ b/dist/data/manage-typed-array.js @@ -0,0 +1,20 @@ +export default function manageTypedArray(host, cls, value) { + const existing = new Map() + for (let i = 0; i list.length) { + host.lastChild.destroy() + } + while (host.children.length < list.length) { + const comp = cls.create() + host.append(comp) + } + for (let i = 0; i { + if (value === boundSubclassGetter()) return // skip identical + boundSubclassSetter(value) + Signal.broadcast(instance, Signal.CHANGE, name) + }, + get: boundSubclassGetter, + configurable: true, + enumerable: true + } + Object.defineProperty(instance, name, proxyDescriptor) + } + } +} \ No newline at end of file diff --git a/dist/glue/ensure-type.js b/dist/glue/ensure-type.js new file mode 100644 index 0000000..5316206 --- /dev/null +++ b/dist/glue/ensure-type.js @@ -0,0 +1,8 @@ +export default function ensureType(type, value) { + if (value === null || value === undefined) return null + if (value instanceof type) return value + if (type === String) return String(value) + if (type === Number) return Number(value) + if (type === Boolean) return !!value + return new type(value) +} \ No newline at end of file diff --git a/dist/glue/ensure-types.js b/dist/glue/ensure-types.js new file mode 100644 index 0000000..a3f30fc --- /dev/null +++ b/dist/glue/ensure-types.js @@ -0,0 +1,5 @@ +import ensureType from "./ensure-type.js"; + +export default function ensureTypes(type, array) { + return array.map(element => ensureType(type, element)) +} \ No newline at end of file diff --git a/dist/glue/signal.js b/dist/glue/signal.js new file mode 100644 index 0000000..d8cb8a5 --- /dev/null +++ b/dist/glue/signal.js @@ -0,0 +1,68 @@ +import Subscription from "./subscription.js" + +export default class Signal { + static DELAY = 0 + static queue = new Set() + static origin = new WeakMap() + static timeout + + static subscribe(origin, callback) { + if (!(callback instanceof Function)) throw new Error("Callback function required") + if (!Signal.origin.has(origin)) Signal.origin.set(origin, new Set()) + Signal.origin.get(origin).add(callback) + return new Subscription(origin, callback) + } + + static unsubscribe(origin, callback) { + if (Signal.origin.has(origin)) { + Signal.origin.get(origin).delete(callback) + if (!Signal.origin.get(origin).size) Signal.origin.delete(origin) + } + } + + static flush() { + for (let signal of Signal.queue) { + signal.callback(signal) + } + Signal.timeout = null + Signal.queue = new Set() + } + + static broadcast(origin, signal = {}) { + if (Signal.origin.has(origin)) { + for (const callback of Signal.origin.get(origin)) { + Signal.queue.add(new Signal({ + path: signal.path, + origin, + callback, + property: signal.property + })) + } + if (!Signal.timeout) Signal.timeout = setTimeout(Signal.flush, Signal.DELAY) + } + } + + #origin + #path + #callback + #property + constructor({origin = null, path = [], callback = ()=>{}, property=null} = {}) { + this.#origin = origin + this.#path = [...path, {origin, property}] + this.#property = property + this.#callback = callback + } + + get origin() { + return this.#origin + } + get path() { + return this.#path + } + get callback() { + return this.#callback + } + get property() { + return this.#property + } +} \ No newline at end of file diff --git a/dist/glue/subscription.js b/dist/glue/subscription.js new file mode 100644 index 0000000..afbcb62 --- /dev/null +++ b/dist/glue/subscription.js @@ -0,0 +1,14 @@ +export default class Subscription { + #origin + #callback + constructor(origin, callback) { + this.#origin = origin + this.#callback = callback + } + get origin() { + return this.#origin + } + get callback() { + return this.#callback + } +} \ No newline at end of file diff --git a/dist/glue/t-array.js b/dist/glue/t-array.js new file mode 100644 index 0000000..52ad89f --- /dev/null +++ b/dist/glue/t-array.js @@ -0,0 +1,128 @@ +import ensureType from "./ensure-type.js" +import ensureTypes from "./ensure-types.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +export default class TArray extends TProperty { + static MUTABLE = ["shift", "pop", "reverse", "sort", "copyWithin"] + #subscriptions = new Map() + #type + constructor(value, type) { + super() + this.#type = type + this.write(value) + } + + #updateSubscriptions() { + const active = new Set() + for (let i = 0; i < this.value.length; i++) { + active.add(this.value[i]) + if (!this.#subscriptions.has(this.value[i])) { + if (typeof this.value[i] === "object") { + const subscription = Signal.subscribe(this.value[i], (signal)=>{ + Signal.broadcast(this, signal) + }) + this.#subscriptions.set(this.value[i], subscription) + } + } + } + for (const [key, value] of this.#subscriptions.entries()) { + if (!active.has(key)) { + Signal.unsubscribe(value.origin, value.callback) + this.#subscriptions.delete(key) + } + } + } + + write(value) { + const type = this.#type + const updateSubscriptions = this.#updateSubscriptions.bind(this) + if (Array.isArray(value)) value = ensureTypes(type, value) + const reference = value + // proxy mutable methods + { + const method = reference.push + value.push = (...elements) => { + const result = method.apply( + reference, + ensureTypes(type, elements) + ) + Signal.broadcast(this) + updateSubscriptions() + return result + } + } + { + const method = reference.unshift + value.unshift = (...elements) => { + const result = method.apply( + reference, + ensureTypes(type, elements) + ) + updateSubscriptions() + return result + } + } + { + const method = reference.splice + value.splice = (start, deleteCount, ...elements) => { + const result = method.call( + reference, + start, + deleteCount, + ...ensureTypes(type, elements) + ) + Signal.broadcast(this) + updateSubscriptions() + return result + } + } + { + const method = reference.fill + value.fill = (element, start, end) => { + const result = method.call( + reference, + ensureType(element), + start, + end + ) + Signal.broadcast(this) + updateSubscriptions() + return result + } + } + TArray.MUTABLE.forEach((name)=>{ + const method = value[name] + reference[name] = (...args) => { + const result = method.call(reference, ...args) + Signal.broadcast(this) + updateSubscriptions() + return result + } + }) + const self = this + + // add dynamic numerical property proxy + value = new Proxy(value, { + set: function(target, property, value) { + if (property === 'length' || isNaN(property)) { + target[property] = value; + } else { + target[property] = ensureType(type, value) + Signal.broadcast(self) + updateSubscriptions() + } + return true + }, + deleteProperty: function(target, property) { + delete target[property]; + Signal.broadcast(self) + updateSubscriptions() + return true + } + }) + const returnValue = super.write(value) + updateSubscriptions() + return returnValue + } +} \ No newline at end of file diff --git a/dist/glue/t-boolean.js b/dist/glue/t-boolean.js new file mode 100644 index 0000000..0955ec9 --- /dev/null +++ b/dist/glue/t-boolean.js @@ -0,0 +1,8 @@ +import TProperty from "./t-property.js" + +export default class TBoolean extends TProperty { + constructor(value) { + super() + this.write(!!value) + } +} \ No newline at end of file diff --git a/dist/glue/t-instance.js b/dist/glue/t-instance.js new file mode 100644 index 0000000..12fb8d3 --- /dev/null +++ b/dist/glue/t-instance.js @@ -0,0 +1,24 @@ +import ensureType from "./ensure-type.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +export default class TInstance extends TProperty { + #type + #subscription + constructor(value, type) { + super() + this.#type = type + this.write(value) + } + + write(value) { + value = ensureType(this.#type, value) + if (this.#subscription) Signal.unsubscribe(this.#subscription.origin, this.#subscription.callback) + if (value) { + this.#subscription = Signal.subscribe(value, (signal)=>{ + Signal.broadcast(this, signal) + }) + } + return super.write(value) + } +} \ No newline at end of file diff --git a/dist/glue/t-number.js b/dist/glue/t-number.js new file mode 100644 index 0000000..cb95b19 --- /dev/null +++ b/dist/glue/t-number.js @@ -0,0 +1,8 @@ +import TProperty from "./t-property.js" + +export default class TNumber extends TProperty { + constructor(value) { + super() + this.write(Number(value)) + } +} \ No newline at end of file diff --git a/dist/glue/t-object.js b/dist/glue/t-object.js new file mode 100644 index 0000000..cb695bd --- /dev/null +++ b/dist/glue/t-object.js @@ -0,0 +1,62 @@ +import ensureType from "./ensure-type.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +export default class TObject extends TProperty { + #type = String + #subscriptions = new Map() + constructor(value, type) { + super() + this.#type = type + this.write(value) + } + + #updateSubscriptions() { + const active = new Set() + for (let key in this.value) { + active.add(key) + let item = this.value[key] + if (!this.#subscriptions.has(key)) { + if (typeof item === "object") { + const subscription = Signal.subscribe(item, (signal)=>{ + Signal.broadcast(this, signal) + }) + this.#subscriptions.set(key, subscription) + } + } + } + for (const [key, value] of this.#subscriptions.entries()) { + if (!active.has(key)) { + Signal.unsubscribe(value.origin, value.callback) + this.#subscriptions.delete(key) + } + } + } + + write(value) { + const map = value || {} + const type = this.#type + for (let [key, item] of Object.entries(value)) { + value[key] = ensureType(this.#type, item) + } + + const updateSubscriptions = this.#updateSubscriptions.bind(this) + const self = this + + const proxy = new Proxy(map, { + set: function(target, property, value) { + target[property] = ensureType(type, value) + Signal.broadcast(self) + updateSubscriptions() + return true + }, + deleteProperty: function(target, property) { + delete target[property] + Signal.broadcast(self) + updateSubscriptions() + return true + } + }) + return super.write(proxy) + } +} \ No newline at end of file diff --git a/dist/glue/t-property.js b/dist/glue/t-property.js new file mode 100644 index 0000000..70ef3db --- /dev/null +++ b/dist/glue/t-property.js @@ -0,0 +1,24 @@ +export default class TProperty { + + #value + + constructor() { + + } + + write(value) { + this.value = value + } + + read() { + return this.value + } + + get value() { + return this.#value + } + + set value(value) { + return this.#value = value + } +} \ No newline at end of file diff --git a/dist/glue/t-string.js b/dist/glue/t-string.js new file mode 100644 index 0000000..caaff67 --- /dev/null +++ b/dist/glue/t-string.js @@ -0,0 +1,8 @@ +import TProperty from "./t-property.js" + +export default class TString extends TProperty { + constructor(value) { + super() + this.write(String(value)) + } +} \ No newline at end of file diff --git a/dist/glue/t.js b/dist/glue/t.js new file mode 100644 index 0000000..e76751a --- /dev/null +++ b/dist/glue/t.js @@ -0,0 +1,29 @@ +import TArray from "./t-array.js" +import TBoolean from "./t-boolean.js" +import TObject from "./t-object.js" +import TNumber from "./t-number.js" +import TInstance from "./t-instance.js" +import TString from "./t-string.js" + +const typeMap = new Map([ + [String, TString], + [Number, TNumber], + [Boolean, TBoolean] +]) + +export function T(type, value) { + if (typeMap.has(type)){ + return new (typeMap.get(type))(value) + } + return new TInstance(value, type) +} + +export function A(type, value) { + if (!Array.isArray(value)) value = [] + return new TArray(value, type) +} + +export function O(type, value) { + if (typeof value !== 'object') value = {} + return new TObject(value, type) +} \ No newline at end of file diff --git a/dist/glue/unwatch.js b/dist/glue/unwatch.js new file mode 100644 index 0000000..42723e1 --- /dev/null +++ b/dist/glue/unwatch.js @@ -0,0 +1,18 @@ +import Signal from "./signal.js" +import { references } from "./watch.js" + +export default function unwatch(reference, name) { + if (!references.has(reference)) return + if (!name) { + for (let [name, subscription] of references.get(reference)) { + Signal.unsubscribe(subscription.origin, subscription.callback) + references.get(reference).delete(name) + if (!references.get(reference).size) references.delete(reference) + } + } else if (references.get(reference).has(name)){ + const subscription = references.get(reference).get(name) + Signal.unsubscribe(subscription.origin, subscription.callback) + references.get(reference).delete(name) + if (!references.get(reference).size) references.delete(reference) + } +} \ No newline at end of file diff --git a/dist/glue/watch.js b/dist/glue/watch.js new file mode 100644 index 0000000..377faef --- /dev/null +++ b/dist/glue/watch.js @@ -0,0 +1,29 @@ +import getProperties from "../data/get-properties.js" +import Signal from "./signal.js" + +export const references = new Map() + +export default function watch(reference, name, callback) { + const properties = getProperties(reference) + if (!properties[name]) return + const descriptor = properties[name] + if (descriptor && descriptor.set) { + const setter = descriptor.set.bind(reference) + descriptor.set = (value) => { + if (references.has(reference) && references.get(reference).has(name)) { + const subscription = references.get(reference).get(name) + Signal.unsubscribe(subscription.origin, subscription.callback) + references.get(reference).delete(name) + if (!references.get(reference).size) references.delete(reference) + } + setter(value) + if (value) { + if (!references.has(reference)) references.set(reference, new Map()) + references.get(reference).set(name, Signal.subscribe(value, callback)) + } + callback(new Signal({origin: value, callback})) + } + Object.defineProperty(reference, name, descriptor) + } + +} \ No newline at end of file diff --git a/dist/glue/wrap.js b/dist/glue/wrap.js new file mode 100644 index 0000000..d221886 --- /dev/null +++ b/dist/glue/wrap.js @@ -0,0 +1,55 @@ +import getProperties from "../data/get-properties.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +function wrapT(instance, name, descriptor) { + const reference = descriptor.get.apply(instance) + return { + ...descriptor, + set: (value)=> { + const before = reference.read() + reference.write(value) + if (before != reference.read()) Signal.broadcast(instance, {property: name}) + }, + get: () => { + return reference.read() + }, + configurable: false, + enumerable: true + } +} + +function wrapProperty(instance, name, descriptor) { + const setter = descriptor.set.bind(instance) + return { + ...descriptor, + set: (value)=> { + setter(value) + Signal.broadcast(instance, {property: name}) + }, + configurable: false, + enumerable: true + } +} + + +export default function wrap(instance) { + const properties = getProperties(instance) + for (let [name, descriptor] of Object.entries(properties)) { + if (descriptor.set && descriptor.get) { + const initialValue = descriptor.get.apply(instance) + if (initialValue instanceof TProperty) { + descriptor = wrapT(instance, name, descriptor) + Signal.subscribe(initialValue, (signal)=>{ + // tProperty is removed from path + Signal.broadcast(instance, {path: [...signal.path.slice(0,-1)], property: name}) + }) + } else { + descriptor = wrapProperty(instance, name, descriptor) + } + Object.defineProperty(instance, name, descriptor) + } + } + return instance + +} \ No newline at end of file diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000..c82e95c --- /dev/null +++ b/dist/index.html @@ -0,0 +1,42 @@ + + + + + + + + AWSM - AwesomeWaveSplineMachine + + + + + + + + + + diff --git a/dist/math/calculate-angle-between.js b/dist/math/calculate-angle-between.js new file mode 100644 index 0000000..6a024dc --- /dev/null +++ b/dist/math/calculate-angle-between.js @@ -0,0 +1,9 @@ +import wrapAngle from "./wrap-angle.js" +import { TAU } from "./contants.js" + +export default function calculateAngleBetween(a, b) { + a = wrapAngle(a) + b = wrapAngle(b) + const delta = (b - a + TAU) % TAU + return delta +} \ No newline at end of file diff --git a/dist/math/calculate-angle.js b/dist/math/calculate-angle.js new file mode 100644 index 0000000..8b6f00d --- /dev/null +++ b/dist/math/calculate-angle.js @@ -0,0 +1,3 @@ +export default function calculateAngle({x = 0, y = 0}) { + return Math.atan2(y ,x); +} \ No newline at end of file diff --git a/dist/math/calculate-circle-point.js b/dist/math/calculate-circle-point.js new file mode 100644 index 0000000..308b4c9 --- /dev/null +++ b/dist/math/calculate-circle-point.js @@ -0,0 +1,7 @@ + +export default function calculateCirclePoint(radius, angle) { + return { + x: radius * Math.cos(angle), + y: radius * Math.sin(angle) + } +} \ No newline at end of file diff --git a/dist/math/calculate-distance.js b/dist/math/calculate-distance.js new file mode 100644 index 0000000..e7e852a --- /dev/null +++ b/dist/math/calculate-distance.js @@ -0,0 +1,5 @@ +export default function calculateDistance(a = {x: 0, y: 0}, b = {x: 0, y: 0}, weight = {x:1, y:1}) { + const dx = (b.x - a.x) * weight.x + const dy = (b.y - a.y) * weight.y + return Math.sqrt(dx * dx + dy * dy) +} \ No newline at end of file diff --git a/dist/math/calculate-length.js b/dist/math/calculate-length.js new file mode 100644 index 0000000..8b703c8 --- /dev/null +++ b/dist/math/calculate-length.js @@ -0,0 +1,3 @@ +export default function calculateLength(a, b) { + return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)) +} \ No newline at end of file diff --git a/dist/math/calculate-pole-value.js b/dist/math/calculate-pole-value.js new file mode 100644 index 0000000..e30a6b4 --- /dev/null +++ b/dist/math/calculate-pole-value.js @@ -0,0 +1,10 @@ +import Point from "../model/point.js" +import { TAU } from "./contants.js" +import rotatePoint from "./rotate-point.js" + +export default function calculatePoleValue(pole, poles, position) { + const segmentAngle = TAU / poles + let rotated = rotatePoint(new Point(), position, pole * segmentAngle ) + let len = Math.max(0, Math.min(1, (rotated.y+1)/2)) + return len +} \ No newline at end of file diff --git a/dist/math/calculate-q.js b/dist/math/calculate-q.js new file mode 100644 index 0000000..b426c6d --- /dev/null +++ b/dist/math/calculate-q.js @@ -0,0 +1,5 @@ +export default function calcQ(a, b, x) { + const dx = (1 + (b - a)) % 1 + const xn = ((1 + (x - a)) % 1) / dx + return xn +} \ No newline at end of file diff --git a/dist/math/compare-float.js b/dist/math/compare-float.js new file mode 100644 index 0000000..d988af5 --- /dev/null +++ b/dist/math/compare-float.js @@ -0,0 +1,3 @@ +export default function compareFloat(a,b, tolerance = 1e-8) { + return Math.abs(a - b) < tolerance +} \ No newline at end of file diff --git a/dist/math/contants.js b/dist/math/contants.js new file mode 100644 index 0000000..70a0622 --- /dev/null +++ b/dist/math/contants.js @@ -0,0 +1 @@ +export const TAU = Math.PI * 2 \ No newline at end of file diff --git a/dist/math/from-fraction.js b/dist/math/from-fraction.js new file mode 100644 index 0000000..5f13869 --- /dev/null +++ b/dist/math/from-fraction.js @@ -0,0 +1,11 @@ +export function fromFraction(str) { + const match = /([0-9]+)(\/([0-9]+))?/.exec(str) + let val = 1 + if (match.length) { + const num = parseInt(match[1]) + const denom = parseInt(match[3]) + if (!Number.isNaN(num)) val = num + if (!Number.isNaN(denom) && denom > 0) val /= denom + } + return val +} \ No newline at end of file diff --git a/dist/math/interpolate-exponential.js b/dist/math/interpolate-exponential.js new file mode 100644 index 0000000..11ce3b3 --- /dev/null +++ b/dist/math/interpolate-exponential.js @@ -0,0 +1,7 @@ +import interpolateLinear from "./interpolate-linear.js" + +export default function interpolateExponential(a, b, e, q) { + if (e == 1) return interpolateLinear(a, b, q) // is linear + if (q < .5) return interpolateLinear(a, b, Math.pow((q * 2), e) / 2) + return interpolateLinear(a, b, 1 - Math.pow(((1 - q) * 2), e) / 2) +} \ No newline at end of file diff --git a/dist/math/interpolate-linear.js b/dist/math/interpolate-linear.js new file mode 100644 index 0000000..6cd3bd7 --- /dev/null +++ b/dist/math/interpolate-linear.js @@ -0,0 +1,3 @@ +export default function interpolateLinear(a, b, q) { + return a + (b - a) * q; +} \ No newline at end of file diff --git a/dist/math/interpolate-point.js b/dist/math/interpolate-point.js new file mode 100644 index 0000000..f05811a --- /dev/null +++ b/dist/math/interpolate-point.js @@ -0,0 +1,8 @@ +import interpolateLinear from "./interpolate-linear.js"; + +export default function interpolatePoint(a, b, q) { + return { + x: interpolateLinear(a.x, b.x, q), + y: interpolateLinear(a.y, b.y, q) + } +} \ No newline at end of file diff --git a/dist/math/multiply-exponential-quotient.js b/dist/math/multiply-exponential-quotient.js new file mode 100644 index 0000000..3406a0c --- /dev/null +++ b/dist/math/multiply-exponential-quotient.js @@ -0,0 +1,3 @@ +export default function multiplyExponentialQuotient(x, {n=1, o=1} = {}) { + return x * Math.pow(2, n/o) +} \ No newline at end of file diff --git a/dist/math/normalize.js b/dist/math/normalize.js new file mode 100644 index 0000000..6a76077 --- /dev/null +++ b/dist/math/normalize.js @@ -0,0 +1,3 @@ +export default function normalize(value, {min = 0, max = 1} = {}) { + return value * (max-min) + min +} \ No newline at end of file diff --git a/dist/math/quantize.js b/dist/math/quantize.js new file mode 100644 index 0000000..f7c3b01 --- /dev/null +++ b/dist/math/quantize.js @@ -0,0 +1,5 @@ +export default function quantize(value, quantize = Number.MAX_SAFE_INTEGER, threshold = 0, override = false) { + if (override || quantize >= Number.MAX_SAFE_INTEGER) return value + let t = threshold * .5 + .5 + return ((t + value * quantize) | 0) / quantize +} \ No newline at end of file diff --git a/dist/math/rotate-point.js b/dist/math/rotate-point.js new file mode 100644 index 0000000..cc62408 --- /dev/null +++ b/dist/math/rotate-point.js @@ -0,0 +1,9 @@ + +export default function rotatePoint(c, p, radians) { + const cos = Math.cos(radians) + const sin = Math.sin(radians) + return { + x: (cos * (p.x - c.x)) + (sin * (p.y - c.y)) + c.x, + y: (cos * (p.y - c.y)) - (sin * (p.x - c.x)) + c.y + } +} \ No newline at end of file diff --git a/dist/math/to-fraction.js b/dist/math/to-fraction.js new file mode 100644 index 0000000..2546392 --- /dev/null +++ b/dist/math/to-fraction.js @@ -0,0 +1,16 @@ +// pow: 6 = 1/2^6 = 1/64 +export default function toFraction(val, pow = 6) { + let denom = Math.pow(2, pow) + const sign = val < 0 ? '-' : '' + val = Math.abs(val) + const stp = 1 / denom + const int = Math.floor(val) + let num = Math.round((val - int) / stp) + if (int == val || num == 0) return `${sign}${int}` + while (num > 0 && num % 2 == 0) { + num /= 2 + denom /= 2 + } + if (int != 0) return `${sign}${int} ${num}/${denom}` + else return `${sign}${num}/${denom}` +} diff --git a/dist/math/translate-point.js b/dist/math/translate-point.js new file mode 100644 index 0000000..4a788df --- /dev/null +++ b/dist/math/translate-point.js @@ -0,0 +1,6 @@ +export default function translatePoint(a, b) { + return { + x: a.x + b.x, + y: a.y + b.y + } +} \ No newline at end of file diff --git a/dist/math/wrap-angle.js b/dist/math/wrap-angle.js new file mode 100644 index 0000000..6058733 --- /dev/null +++ b/dist/math/wrap-angle.js @@ -0,0 +1,5 @@ +import { TAU } from "./contants.js" + +export default function wrapAngle(value) { + return (value + TAU) % TAU +} \ No newline at end of file diff --git a/dist/model/audio-metrics.js b/dist/model/audio-metrics.js new file mode 100644 index 0000000..3194f2b --- /dev/null +++ b/dist/model/audio-metrics.js @@ -0,0 +1,25 @@ + + +export default class AudioMetrics { + #frame = new Uint8Array() + #callback + constructor() { + //wrap(this) + } + + get callback() { + return this.#callback + } + + set callback(value) { + this.#callback = value + } + + get frame() { + return this.#frame + } + + set frame(value) { + this.#frame = value + } +} \ No newline at end of file diff --git a/dist/model/channel.js b/dist/model/channel.js new file mode 100644 index 0000000..c81c673 --- /dev/null +++ b/dist/model/channel.js @@ -0,0 +1,97 @@ +import {A, T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import AudioMetrics from "./audio-metrics.js" +import Dynamics from "./dynamics.js" +import Entity from "./entity.js" +import Voice from "./voice.js" + +export default class Channel extends Entity { + static ACTIVE = "active" + static TRIGGER_RELEASE = "trigger-release" + static RELEASE = "release" + static DELETE = "delete" + #voices = A(Voice, []) + #gain = T(Number, 1.) + #activeVoice = T(String, "") + #name = T(String, randomName()) + #state = T(String, Channel.ACTIVE) + #release = T(Number, .1) + #dynamics = T(Dynamics, {}) + #audioMetrics = new AudioMetrics() + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + get state() { + return this.#state + } + + set state(value) { + this.#state = value + } + + get release() { + return this.#release + } + + set release(value) { + this.#release = value + } + + get voices() { + return this.#voices + } + + set voices(value) { + this.#voices = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get activeVoice() { + return this.#activeVoice + } + + set activeVoice(value) { + this.#activeVoice = value + } + + get dynamics() { + return this.#dynamics + } + + set dynamics(value) { + this.#dynamics = value + } + + get audioMetrics() { + return this.#audioMetrics + } + + findActiveVoice() { + return this.findVoice(this.activeVoice) + } + + findVoice(id) { + return this.voices.find(voice => voice.id === id) + } + +} \ No newline at end of file diff --git a/dist/model/default-session.js b/dist/model/default-session.js new file mode 100644 index 0000000..a49373d --- /dev/null +++ b/dist/model/default-session.js @@ -0,0 +1,1394 @@ +export default function defaultSession() { + return { + "path": [], + "dynamics": { + "threshold": 0.349129697812655, + "scale": 0.38496777395045084, + "potential": 0, + "id": "75261d5c-940e-4d85-9761-e66a178c3625" + }, + "views": [ + { + "path": [], + "navigationCollapsed": true, + "name": "Udriduwo Osnoy", + "id": "b4715183-d30f-4764-8770-2eaef64b2733" + }, + { + "path": [ + "7d8151f4-5ed4-4407-a9e2-662630b1b96e" + ], + "navigationCollapsed": false, + "name": "Aju Snauple", + "id": "21b29821-a9ce-4925-943f-598c481dc48e" + }, + { + "path": [ + "0fcb027f-b166-4da3-8e98-d6daa136a163", + "9371e92c-9c17-4c41-ad60-232e06573e43" + ], + "navigationCollapsed": false, + "name": "Austoul Au", + "id": "6249f2a8-6a9e-4525-bddb-cb4c1f6c7965" + }, + { + "path": [ + "be8dc91c-1c3e-42c8-8337-a903177f615f", + "fbdbca22-274a-4c2b-b7ec-0a435d97efd2", + "gain" + ], + "navigationCollapsed": false, + "name": "Uipreiv Eyb", + "id": "c832e68b-62f3-48b2-a258-63a9c5cf59c0" + } + ], + "mode": "storage", + "activeView": 0, + "name": "Demo", + "channels": [ + { + "name": "Earespu Clou", + "state": "active", + "release": 0.1, + "voices": [ + { + "oscillator": { + "length": 0.5, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.0010143577509948987, + "y": 0.4989980061848962, + "e": 1, + "id": "d9f4c031-901f-4a02-bdae-7ac7c108a404" + }, + { + "x": 0.007359855533129567, + "y": 1, + "e": 1, + "id": "2e11e0e7-a104-42f7-b7c5-4989fe20493f" + }, + { + "x": 0.010773426327540525, + "y": 0.05595143636067705, + "e": 1, + "id": "73c39e01-3087-445f-80f9-97117ee63c75" + }, + { + "x": 0.014791458973981264, + "y": 0.9363412857055664, + "e": 1, + "id": "14748514-146f-4e56-8ec8-b4562eb00f02" + }, + { + "x": 0.026395144838690543, + "y": 0.07840315500895176, + "e": 1, + "id": "71b0bad8-c04f-4284-98bf-03a1c0236f1f" + }, + { + "x": 0.03762604377999357, + "y": 0.8514207204182936, + "e": 1, + "id": "fda8e719-5349-4d40-a828-3b5650639417" + }, + { + "x": 0.05139424279680993, + "y": 0.09842809041341129, + "e": 1, + "id": "66168172-ff4c-4305-919e-1b1249ad3c96" + }, + { + "x": 0.08752013044323004, + "y": 0.8994388580322267, + "e": 1, + "id": "b7eaf147-c5a0-4dd3-9c40-c0127b360a34" + }, + { + "x": 0.12376397338390444, + "y": 0.2208547592163084, + "e": 1, + "id": "7e43dd58-3477-4bcd-aef2-99424bc5071f" + }, + { + "x": 0.24738610615034085, + "y": 0.644672711690267, + "e": 1, + "id": "478694f9-b875-4889-9056-806db93169ad" + }, + { + "x": 0.39602545871077854, + "y": 0.5020783742268882, + "e": 1, + "id": "51c74b73-c865-4bbe-900d-b22ebf87010d" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "fd6df856-add6-49cb-bddf-9d4e02d80b8e" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "86158850-12bc-4e53-87bd-e361e6ee63e3" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "6f5c4b38-b769-43cf-a687-565193b4a4dd" + }, + "e": 2.35, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 0.4004503526937189, + "viewPosition": 0, + "id": "5557abc6-6499-4033-8f5f-345af16dcc1b" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": { + "length": 0.017161351139667155, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.1029294331868491, + "y": 0, + "e": 1, + "id": "45e5381c-43d0-49a6-a352-07d6d893e1b3" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "64094b50-cf66-4ba6-989d-566f13a39236" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "f2417c9a-9e97-4077-8be3-d3f97ae8a636" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "013b4e66-9570-4417-acf7-dba97931448b" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "247672d4-add9-4b6b-8f1d-36a4e5977360" + }, + "e": 2.84, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "1c972134-bf6d-4a76-bb28-fb3fa74c1adc" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "84811779-f604-4f02-b060-5be0313ef0b3" + }, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "1833b7cf-7ca0-42d5-91a9-88b7e8838e09" + }, + "name": "Ie Aysweu", + "gain": 0.5, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "7110ada3-c782-4a7e-987c-26fe547205fc" + }, + { + "oscillator": { + "length": 0.25, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.005726814270019531, + "y": 0.499276161193848, + "e": 1, + "id": "a417f8e9-1813-4005-9b2c-4f9bf27f9812" + }, + { + "x": 0.013080808851455128, + "y": 0.9068705240885417, + "e": 1, + "id": "7a0f0b6c-629b-47dd-8fac-754b7c35aed3" + }, + { + "x": 0.019806649949815958, + "y": 0.03876590728759763, + "e": 1, + "id": "6f9af57b-4960-4e64-8da8-e3691fde974a" + }, + { + "x": 0.04198858473036249, + "y": 0.9609591166178384, + "e": 1, + "id": "e4069bc8-ec89-47f6-a9fb-5e18ff2d5366" + }, + { + "x": 0.04583115047879027, + "y": 0.05836359659830733, + "e": 1, + "id": "41246558-63bf-4e47-a114-6943dfd37698" + }, + { + "x": 0.05918449825710925, + "y": 0.9942452112833647, + "e": 1, + "id": "586fbffa-9f23-42ff-843a-cf01b4a3cae3" + }, + { + "x": 0.06579240163167532, + "y": 0.02501010894775375, + "e": 1, + "id": "c6572915-641f-496d-9137-d0dd4ffe88d5" + }, + { + "x": 0.07741599612765926, + "y": 0.9438126881917317, + "e": 1, + "id": "bc82d405-2094-4fc4-805f-37b822aca6ff" + }, + { + "x": 0.09471691979302488, + "y": 0.11187203725179029, + "e": 1, + "id": "f512a954-787f-4040-9ac6-b5aff7f39ada" + }, + { + "x": 0.12103504604763593, + "y": 0.8723354339599607, + "e": 1, + "id": "c310c2c4-9ca3-4f8b-a191-0615bb767c2f" + }, + { + "x": 0.21491305033365848, + "y": 0.14733664194742838, + "e": 1, + "id": "5761c52b-b20e-4c9a-b771-17ba32aa8434" + }, + { + "x": 0.31263404422336194, + "y": 0.7578954696655276, + "e": 1, + "id": "590b5f2a-3707-4fe9-9533-3bed618111db" + }, + { + "x": 0.5011656019422737, + "y": 0.5021295547485354, + "e": 1, + "id": "13199317-ec56-4bb6-be5e-03d649ccfcee" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "d25fd705-1788-47c9-8118-eaa3f0c4cce0" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "082d55d3-dafa-476c-bd43-3b78b0329abf" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "28a638fc-1629-48fc-8822-f13b8c457c4a" + }, + "e": 3, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "90d49fa0-75de-4379-9bab-9ac6d6ccfa52" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": { + "length": 0.008580675569833577, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.21338992648654576, + "y": 0.2439339955647786, + "e": 1, + "id": "5a6f58d0-23ed-43ea-a8ea-0793ec405221" + }, + { + "x": 0.704262309604222, + "y": 0.6567325592041011, + "e": 1, + "id": "68efaeea-4145-4a7e-9a68-3add2636fb29" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "873926b6-6e27-4242-9798-cf0e0ed24a32" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "ad581199-5c9b-42c4-9946-e74393ede8f3" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "f895418f-e509-469b-9e9d-61f1c17ab230" + }, + "e": 3.16, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "bd23305a-d9b3-49b8-abb6-68d1f9f8f646" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "8cc643e4-7b52-4a5d-b1a8-27ad659e5f1c" + }, + "em": null, + "sx": null, + "sy": null, + "gain": { + "length": 2.4, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.000027868482801451933, + "y": 0.005122184753417969, + "e": 1, + "id": "ed83ad0c-8ac7-437f-8193-c85db885f66b" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "e9753378-06f4-4ba5-beb4-4d0ced54a9f7" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "4e9faa99-2f4b-48ae-8aef-0e163ef89511" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "5e7cfde5-0b0d-4c57-b4ae-bd3523b35306" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "18c4c764-fe84-4605-aed8-596e3ec7983c" + }, + "e": 7.76, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "48e57cea-1da4-42aa-8397-b838bc7c48ae" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "75477d50-783e-49b2-872e-df24d736eb72" + }, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "24436af1-32a8-4bb5-8c66-272d929f641f" + }, + "name": "Oikneu Blespo", + "gain": 0.5, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "8af95214-7ece-4fee-9c9d-60dddf38b713" + } + ], + "gain": 1, + "activeVoice": "", + "dynamics": { + "threshold": 0.2187051292650003, + "scale": 0.3621376901024899, + "potential": 0.472186841488431, + "id": "93491cbf-b0cc-4aa7-8721-9a8854d29b8a" + }, + "id": "7d8151f4-5ed4-4407-a9e2-662630b1b96e" + }, + { + "name": "Eubre Ee", + "state": "active", + "release": 0.1, + "voices": [ + { + "oscillator": { + "length": 0.01362097342615165, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0, + "y": 0, + "e": 1, + "id": "a148103e-0496-4558-a2ce-9641c2009101" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "c5927923-6243-44d9-b781-7186fa347458" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "3238ab8d-3c7b-43f4-bd9c-efd0f2f1389d" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "425f8c7e-9179-4375-b7c7-de744adf3d4d" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "d6b738f5-6fc3-4b51-bc1a-5fb2638bcd75" + }, + "e": 2.39, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "fa5fb2b7-a8f2-485e-abb6-b78fd3ab3b37" + }, + "fm": { + "length": 9.6, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.125, + "y": 0.5, + "e": 1, + "id": "547eff7b-5e1c-4128-8ac3-aa474966a430" + }, + { + "x": 0.25, + "y": 0.625, + "e": 1, + "id": "f447ad3d-1a59-4271-b8f5-e32d6bdb4597" + }, + { + "x": 0.375, + "y": 0.5, + "e": 1, + "id": "471c5dc7-f679-4aee-92da-ea2c54f52140" + }, + { + "x": 0.5, + "y": 0.4166666666666667, + "e": 1, + "id": "4e69082e-c2bd-4bf1-af49-4ffa1a812e84" + }, + { + "x": 0.625, + "y": 0.5, + "e": 1, + "id": "177dcfff-5778-439b-9dce-ca74da8c9277" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "14fa6206-cb46-4aef-9f1b-7a7346e3c000" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "df1468d1-a05d-451d-96cd-240b5fac6993" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "5356d2f3-0967-42a4-8c7a-494fc224a0b9" + }, + "e": 1000, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 8, + "gridXThreshold": 0, + "gridY": 24, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "ff360c51-4447-43eb-8b6a-1a08a67d67a8" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "392f55d2-b2fe-4823-811a-d68ca0e50666" + }, + "fmRange": 2, + "transpose": null, + "am": null, + "em": { + "length": 9.6, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.125, + "y": 0.33648459116617835, + "e": 1, + "id": "4f3ba4a2-3bcc-441f-8f4d-62e436b52352" + }, + { + "x": 0.375, + "y": 0.9756914774576826, + "e": 1, + "id": "7e48bb99-bd8a-43ce-9bdb-bc7f2e4db60e" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "7d76b48e-5613-4539-8eec-b5311e2f7d73" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "60aee2da-ef52-4baa-8a03-3a54c2535f8c" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "c29f4763-9ef6-4834-805d-3a5a18b69e11" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 8, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "67f8dc20-d2ea-4502-820d-88141c4f3d09" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "19801666-cd16-42c3-b7a1-c1d31f667ec3" + }, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "b432c48a-f2d3-4d6e-a37d-15036eb17ce0" + }, + "name": "Ui Oashee", + "gain": 0.5, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "9371e92c-9c17-4c41-ad60-232e06573e43" + } + ], + "gain": 0.8722687054057093, + "activeVoice": "", + "dynamics": { + "threshold": 0.30829745376588447, + "scale": 0.4931716396287149, + "potential": 0.3933952664454105, + "id": "f2df0cad-6d71-474e-abec-7dec0d312aed" + }, + "id": "0fcb027f-b166-4da3-8e98-d6daa136a163" + }, + { + "name": "Ee Stray", + "state": "active", + "release": 0.1, + "voices": [ + { + "oscillator": { + "length": 0.0021451688924583943, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0, + "y": 0, + "e": 1, + "id": "04e39018-92c8-43ab-b590-122472038296" + }, + { + "x": 0.5159289395595947, + "y": 1, + "e": 1, + "id": "ad0a6e8d-878c-42fd-a516-fc932f6279b8" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "decfb419-8b60-403e-b475-2adc7577744b" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "b8666d08-4216-4a5b-8544-8854efe32ac9" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "10724937-b219-4d6c-81d4-7b47fdc67d1a" + }, + "e": 4.8100000000000005, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "4addc060-4afd-4be8-b9a8-85f5333311ca" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": { + "length": 2.4, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.3125, + "y": 0, + "e": 1, + "id": "2f6a68fc-f2a5-473c-be0f-0a95df3f68ec" + }, + { + "x": 0.5, + "y": 0.8668719927469877, + "e": 1, + "id": "d070ab04-209c-4897-b47d-a3ff95479062" + }, + { + "x": 1, + "y": 0.006402969360351563, + "e": 1, + "id": "4a30e08f-2ccf-413a-b6b9-d93b93e63438" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "5c79efcc-c048-405b-944b-edae6a5d4101" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "e032aa21-82d1-43fe-9052-f7dfa7b717e0" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "925b1a95-478d-4402-b994-373f2c3a73f2" + }, + "e": 3.08, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 16, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "74f79471-ae1a-402d-b72c-8a8576feef3f" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "ed597a7b-a06e-468d-9a7e-19e68aa56224" + }, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "47d1e8ee-8ad7-4f98-ba72-2c4f9b22aafe" + }, + "name": "Ezu Cleysle", + "gain": 0.12437363679347828, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "fbdbca22-274a-4c2b-b7ec-0a435d97efd2" + } + ], + "gain": 0.1845072824868422, + "activeVoice": "", + "dynamics": { + "threshold": 0.4938849770556756, + "scale": 0.3831000405849414, + "potential": 0, + "id": "daa5abc9-a8d1-4083-ae5d-d4671c5215fe" + }, + "id": "be8dc91c-1c3e-42c8-8337-a903177f615f" + } + ], + "channelMix": { + "x": 0.03666469029017857, + "y": 0.030744280133928572, + "id": "5a92a719-197c-4c20-83af-c14e2e47d45b" + }, + "main": 0.5071588313070478, + "potential": 0.33, + "mute": false, + "activeChannel": "", + "solo": "", + "keyboardSettings": { + "keys": 24, + "start": 0.00909090909090909, + "increment": 1, + "subdivisions": 12, + "startDriver": "note", + "id": "967b0c80-66c8-40fa-8864-5f87f342d3d2" + }, + "showKeyboardSettings": true, + "settings": { + "tempo": 0.4166666666666667, + "tempoDriver": "bpm", + "id": "d6441151-393b-4e5d-9927-1381521615c1" + }, + "defaults": { + "voice": { + "oscillator": { + "length": 0.00909090909090909, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0, + "y": 0, + "e": 1, + "id": "97666f93-2662-4e1b-98ac-ac4666f42ee9" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "0aeac999-1782-4724-96eb-b1cc52ed6b3b" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "03f442e2-0199-43a4-b919-b8967ab64b01" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "f27e6f85-39bb-483f-ba6d-00c30fbd2925" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "1ebdffa1-71bd-465b-a6c9-007461d034ef" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "82345695-05f5-413e-ad73-739fee387e0c" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "bdf99b30-d15f-4b70-be10-3c5410c2bbf6" + }, + "name": "Eysquooz", + "gain": 0.5, + "state": "idle", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "03aa2d3f-25af-481f-add0-e7db23dfb03a" + }, + "am": { + "length": 0.00909090909090909, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "96d39558-fcd6-447f-b2dc-316b167dfb33" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "715967ca-46e4-457d-a52a-99121688c936" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "430e4279-4f9e-4893-b9b1-15984b3ecc83" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "4b0eb2dc-fb36-46f4-a9a6-e499d0d5c500" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "5b540d28-1f14-4e31-9440-668256629f54" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "ba07b507-b56e-4e99-8ee9-42c38d7e6e6d" + }, + "fm": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 0.5, + "e": 1, + "id": "0e4988c9-b7fa-476e-b2ef-1b9316a18fe4" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "383fa204-c078-4766-aa39-50cb0e501657" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "73cac1dc-3b85-4f7e-bc0c-25237a2e0d2b" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "09c90b7a-c840-4faf-b404-50b6ce45f92f" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "bb68cafd-6400-4581-aa7f-ea4ad13dcbb8" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "695e06be-163e-43e5-8ff2-fa015496935e" + }, + "gain": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "8bf671f3-5911-4d00-9c60-04ce410b5e55" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "ca3176b1-d13c-4449-bdcb-ace966fb0137" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "fb4444e3-9024-4bb0-9a0d-9f1221c6518d" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "c9257aae-ea03-4a9c-82d0-d5aba8f7f60f" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "9e5fc09d-f5d0-44aa-abbc-db8e86024fe6" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "b74eff92-2818-431e-b4da-2b3f44bf8d5a" + }, + "em": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "ddccc59b-c5f9-4c99-8034-aaffe92890b0" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "5dc449fa-1a01-43fe-a8a1-d3660ed93fd6" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "c5bd02a5-e732-4414-befc-2b84fba41319" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "d7d81706-696f-468b-a08d-c2f18a2f7d48" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "d3826b07-1a60-447b-a729-5ae679516b5e" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "ccf28988-1159-465d-81c5-294686266f34" + }, + "sx": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "d9d9adda-4f6e-4ea1-9f05-daf44bf0af5b" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "9397d5d5-3347-4272-bbf5-2615b36bbe6d" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "f4997359-7cda-4387-9f41-f8788b0c3cdd" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "81cd5804-8fef-4509-bbd2-93f302d36674" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "99d91df9-5718-451a-94aa-d18be9d02346" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "3fa6d0bd-f9c8-44b5-a510-f9872abef406" + }, + "transpose": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 0.5, + "e": 1, + "id": "29161cd9-b6dc-4c24-8d59-5faefcd82262" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "8ba68d9f-cd3d-47e0-81b3-82516fc2f971" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "2e05de32-4ab7-4286-9f39-4d97f56fb920" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "80e796f3-e869-4738-b7dc-a0f5205d39bf" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "7da16428-5338-4003-ba12-5e2e4b227ec7" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "3e35417f-f955-4293-8120-b0fe26e801bb" + }, + "id": "6e0880eb-80d6-4814-851e-6aee063a0a44" + }, + "navigationMode": "siblings", + "created": 1708897287648, + "state": "playing", + "keyboardFocus": [ + "be8dc91c-1c3e-42c8-8337-a903177f615f", + "fbdbca22-274a-4c2b-b7ec-0a435d97efd2", + "gain" + ], + "id": "41f3622c-416e-471e-bd34-6205755f00b5", + "tree": { + "type": "session", + "branches": [ + { + "type": "channel", + "branches": [ + { + "type": "voice", + "branches": [ + { + "type": "am", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 1, + "depth": 2 + }, + { + "type": "voice", + "branches": [ + { + "type": "am", + "branches": [], + "span": 1, + "depth": 1 + }, + { + "type": "gain", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 2, + "depth": 2 + } + ], + "span": 3, + "depth": 3 + }, + { + "type": "channel", + "branches": [ + { + "type": "voice", + "branches": [ + { + "type": "fm", + "branches": [], + "span": 1, + "depth": 1 + }, + { + "type": "em", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 2, + "depth": 2 + } + ], + "span": 2, + "depth": 3 + }, + { + "type": "channel", + "branches": [ + { + "type": "voice", + "branches": [ + { + "type": "gain", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 1, + "depth": 2 + } + ], + "span": 1, + "depth": 3 + } + ], + "span": 6, + "depth": 4 + }, + "changed": 1708902557380 + } + +} \ No newline at end of file diff --git a/dist/model/defaults.js b/dist/model/defaults.js new file mode 100644 index 0000000..468caf1 --- /dev/null +++ b/dist/model/defaults.js @@ -0,0 +1,83 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" +import Voice from "./voice.js" +import WaveSplineOscillator from "./wave-spline-oscillator.js" + +export default class Defaults extends Entity { + + #voice = T(Voice, { + gain: 0.5, + oscillator: {length: 1/110, lengthDriver: "note", wave:{points:[{x:0, y:0}, {x:.5, y:1}]}} + }) + #am = T(WaveSplineOscillator, {length: 1/110, lengthDriver: "note", wave:{points:[{x:.5, y:1}]}}) + #fm = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "bar", wave:{points:[{x:.5, y:.5}]}}) + #gain = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:1}]}}) + #em = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:1}]}}) + #sx = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:1}]}}) + #transpose = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:.5}]}}) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get voice() { + return this.#voice + } + + set voice(value) { + this.#voice = value + } + + get am() { + return this.#am + } + + set am(value) { + this.#am = value + } + + get fm() { + return this.#fm + } + + set fm(value) { + this.#fm = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get em() { + return this.#em + } + + set em(value) { + this.#em = value + } + + get sx() { + return this.#sx + } + + set sx(value) { + this.#sx = value + } + + get transpose() { + return this.#transpose + } + + set transpose(value) { + this.#transpose = value + } + + +} \ No newline at end of file diff --git a/dist/model/dynamics.js b/dist/model/dynamics.js new file mode 100644 index 0000000..329e6cc --- /dev/null +++ b/dist/model/dynamics.js @@ -0,0 +1,40 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class Dynamics extends Entity { + + #threshold = T(Number, .5) + #scale = T(Number, 1) + #potential = T(Number, 0) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get threshold() { + return this.#threshold + } + + set threshold(value) { + this.#threshold = value + } + + get scale() { + return this.#scale + } + + set scale(value) { + this.#scale = value + } + + get potential() { + return this.#potential + } + + set potential(value) { + this.#potential = value + } +} \ No newline at end of file diff --git a/dist/model/entity.js b/dist/model/entity.js new file mode 100644 index 0000000..5342225 --- /dev/null +++ b/dist/model/entity.js @@ -0,0 +1,17 @@ +import generateId from "../data/generate-id.js" +import {T} from "../glue/t.js" + +export default class Entity { + #id = T(String, generateId()) + constructor(data = {}) { + Object.assign(this, data) + } + + get id() { + return this.#id + } + + set id(value) { + this.#id = value + } +} \ No newline at end of file diff --git a/dist/model/generate-tree.js b/dist/model/generate-tree.js new file mode 100644 index 0000000..825880b --- /dev/null +++ b/dist/model/generate-tree.js @@ -0,0 +1,37 @@ +export default function generateTree(session) { + let h = 0 + let W = 0 + const sessionBranch = {type: "session", branches: [], span: 0, depth: 1} + session.channels.forEach(channel => { + const channelBranch = {type: "channel", branches: [], span: 0, depth: 1} + sessionBranch.branches.push(channelBranch) + channel.voices.forEach(voice => { + const voiceBranch = generateRecursiveOscillatorTree("voice", voice.oscillator) + channelBranch.branches.push(voiceBranch) + channelBranch.span += voiceBranch.span + channelBranch.depth = Math.max(channelBranch.depth, voiceBranch.depth + 1) + }) + channelBranch.span = Math.max(1, channelBranch.span) + sessionBranch.span += channelBranch.span + sessionBranch.depth = Math.max(sessionBranch.depth, channelBranch.depth + 1) + }) + sessionBranch.span = Math.max(1, sessionBranch.span) + return sessionBranch +} + +function generateRecursiveOscillatorTree(type, oscillator) { + const oscillatorBranch = {type, branches:[], span: 0, depth: 1} + if (oscillator.am) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("am", oscillator.am)) + if (oscillator.fm) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("fm", oscillator.fm)) + if (oscillator.transpose) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("transpose", oscillator.transpose)) + if (oscillator.em) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("em", oscillator.em)) + if (oscillator.sx) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("sx", oscillator.sx)) + if (oscillator.gain) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("gain", oscillator.gain)) + oscillatorBranch.branches.forEach((branch)=>{ + oscillatorBranch.span += branch.span + oscillatorBranch.depth = Math.max(oscillatorBranch.depth, branch.depth +1) + }) + oscillatorBranch.span = Math.max(1, oscillatorBranch.span) + + return oscillatorBranch +} \ No newline at end of file diff --git a/dist/model/keyboard-settings.js b/dist/model/keyboard-settings.js new file mode 100644 index 0000000..438fd92 --- /dev/null +++ b/dist/model/keyboard-settings.js @@ -0,0 +1,60 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class KeyboardSettings extends Entity { + + #keys = T(Number, 24) + #start = T(Number, 1/110) + #increment = T(Number, 1) + #subdivisions = T(Number, 12) + #startDriver = T(String, "note") + + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get keys() { + return this.#keys + } + + set keys(value) { + this.#keys = value + } + + get start() { + return this.#start + } + + set start(value) { + this.#start = value + } + + get increment() { + return this.#increment + } + + set increment(value) { + this.#increment = value + } + + get subdivisions() { + return this.#subdivisions + } + + set subdivisions(value) { + this.#subdivisions = value + } + + get startDriver() { + return this.#startDriver + } + + set startDriver(value) { + this.#startDriver = value + } + +} \ No newline at end of file diff --git a/dist/model/point.js b/dist/model/point.js new file mode 100644 index 0000000..ad74db9 --- /dev/null +++ b/dist/model/point.js @@ -0,0 +1,29 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class Point extends Entity { + #x = T(Number, 0) + #y = T(Number, 0) + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get x() { + return this.#x + } + + set x(value) { + this.#x = value + } + + get y() { + return this.#y + } + + set y(value) { + this.#y = value + } +} \ No newline at end of file diff --git a/dist/model/reset-channel.js b/dist/model/reset-channel.js new file mode 100644 index 0000000..debf643 --- /dev/null +++ b/dist/model/reset-channel.js @@ -0,0 +1,9 @@ +import Channel from "./channel.js" +import resetVoice from "./reset-voice.js" + +export default function resetChannel(channel) { + channel.state = Channel.ACTIVE + channel.voices.forEach(voice=>{ + resetVoice(voice) + }) +} \ No newline at end of file diff --git a/dist/model/reset-state.js b/dist/model/reset-state.js new file mode 100644 index 0000000..4873fc2 --- /dev/null +++ b/dist/model/reset-state.js @@ -0,0 +1,12 @@ +import Channel from "./channel.js"; +import resetChannel from "./reset-channel.js"; +import Session from "./session.js"; +import Voice from "./voice.js"; + +export default function resetState(session) { + if (!session) return + session.state = Session.TRIGGER_PLAY + session.channels.forEach(channel => { + resetChannel(channel) + }); +} \ No newline at end of file diff --git a/dist/model/reset-voice.js b/dist/model/reset-voice.js new file mode 100644 index 0000000..4613a4e --- /dev/null +++ b/dist/model/reset-voice.js @@ -0,0 +1,13 @@ +import Voice from "./voice.js" + +export default function resetVoice(voice) { + if ( + voice.state === Voice.ATTACK + || voice.state === Voice.SUSTAIN + + ) { + voice.state = Voice.TRIGGER_ATTACK + } else if (voice.state === Voice.TRIGGER_RELEASE || voice.state === Voice.RELEASE) { + voice.state = Voice.IDLE + } +} \ No newline at end of file diff --git a/dist/model/session.js b/dist/model/session.js new file mode 100644 index 0000000..9fc3154 --- /dev/null +++ b/dist/model/session.js @@ -0,0 +1,355 @@ +import {A, T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import AudioMetrics from "./audio-metrics.js" +import Channel from "./channel.js" +import Defaults from "./defaults.js" +import Dynamics from "./dynamics.js" +import Entity from "./entity.js" +import KeyboardSettings from "./keyboard-settings.js" +import Point from "./point.js" +import Settings from "./settings.js" +import View from "./view.js" + +const SYNCED_VIEWS = ["bar", "fraction"] + +export default class Session extends Entity { + + static TRIGGER_PAUSE = "trigger-pause" + static TRIGGER_PLAY = "trigger-play" + static PLAY = "play" + static PAUSE = "pause" + static PLAYING = "playing" + static PAUSED = "paused" + + static SIBLINGS = "siblings" + static MULTILINE = "multiline" + static COMPACT = "compact" + + #created = T(Number, Date.now()) + #settings = T(Settings, {}) + #channels = A(Channel, []) + #main = T(Number, 1.) + #mute = T(Boolean, false) + #activeChannel = T(String,"") + #keyboardSettings = T(KeyboardSettings, {}) + #channelMix = T(Point, {x:0, y:0}) + #defaults = T(Defaults, {}) + #dynamics = T(Dynamics, {}) + + #potential = T(Number, 0.33) + + #name = T(String, randomName()) + #path = A(String, []) + #keyboardFocus = A(String, []) + + #navigationMode = T(String, Session.SIBLINGS) + + #views = A(View, [{}]) + #activeView = T(Number, 0) + #mode = T(String, "view") + #showKeyboardSettings = T(Boolean, true) + + #tempoReference = -1 + #audioMetrics = new AudioMetrics() + #solo = T(String,"") + #state = T(String, Session.PLAYING) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get path() { + return this.#path + } + + set path(value) { + this.#path = value + } + + get dynamics() { + return this.#dynamics + } + + set dynamics(value) { + this.#dynamics = value + } + + get views() { + return this.#views + } + + set views(value) { + this.#views = value + } + + get mode() { + return this.#mode + } + + set mode(value) { + this.#mode = value + } + + get activeView() { + return this.#activeView + } + + set activeView(value) { + this.#activeView = value + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + get channels() { + return this.#channels + } + + set channels(value) { + this.#channels = value + } + + get channelMix() { + return this.#channelMix + } + + set channelMix(value) { + this.#channelMix = value + } + + get main() { + return this.#main + } + + set main(value) { + this.#main = value + } + + get potential() { + return this.#potential + } + + set potential(value) { + this.#potential = value + } + + get mute() { + return this.#mute + } + + set mute(value) { + this.#mute = value + } + + get activeChannel() { + return this.#activeChannel + } + + set activeChannel(value) { + this.#activeChannel = value + } + + get solo() { + return this.#solo + } + + set solo(value) { + this.#solo = value + } + + get keyboardSettings() { + return this.#keyboardSettings + } + + set keyboardSettings(value) { + this.#keyboardSettings = value + } + + get showKeyboardSettings() { + return this.#showKeyboardSettings + } + + set showKeyboardSettings(value) { + this.#showKeyboardSettings = value + } + + get settings() { + return this.#settings + } + + set settings(value) { + this.#settings = value + } + + get defaults() { + return this.#defaults + } + + set defaults(value) { + this.#defaults = value + } + + get navigationMode() { + return this.#navigationMode + } + + set navigationMode(value) { + this.#navigationMode = value + } + + get created() { + return this.#created + } + + set created(value) { + this.#created = value + } + + get state() { + return this.#state + } + + set state(value) { + this.#state = value + } + + get audioMetrics() { + return this.#audioMetrics + } + + get keyboardFocus() { + return this.#keyboardFocus + } + + set keyboardFocus(value) { + this.#keyboardFocus = value + } + + getPathReference(path) { + let ref = this + + for(let i=0; i{ + view.path = this.getValidSubpath(view.path) + }) + } + + findActiveChannel() { + return this.findChannel(this.activeChannel) + } + + findChannel(id) { + return this.channels.find(channel => channel.id === id) + } + + voiceSolo(id) { + if (this.solo === id) { + this.solo = "" + } else { + this.solo = id + } + this.channels.forEach(channel => { + channel.voices.forEach(voice => { + if(voice.id === this.solo) { + voice.bus = "solo" + } else { + voice.bus = "main" + } + }) + }) + } + + zeroAll() { + const zeroRecursive = (osc) => { + osc.phase = 0 + if (osc.fm) zeroRecursive(osc.fm) + if (osc.transpose) zeroRecursive(osc.transpose) + if (osc.am) zeroRecursive(osc.am) + if (osc.em) zeroRecursive(osc.em) + if (osc.sx) zeroRecursive(osc.sx) + if (osc.sy) zeroRecursive(osc.sy) + if (osc.gain) zeroRecursive(osc.gain) + } + this.channels.forEach(channel => { + channel.voices.forEach(voice => { + zeroRecursive(voice.oscillator) + }) + }) + } + + syncTempo() { + const multiplyRecursive = (osc, factor) => { + if (osc.tempoSync) osc.length *= factor + if (osc.fm) multiplyRecursive(osc.fm, factor) + if (osc.fm) multiplyRecursive(osc.transpose, factor) + if (osc.am) multiplyRecursive(osc.am, factor) + if (osc.em) multiplyRecursive(osc.em, factor) + if (osc.sx) multiplyRecursive(osc.sx, factor) + if (osc.sy) multiplyRecursive(osc.sy, factor) + if (osc.gain) multiplyRecursive(osc.gain, factor) + } + if (this.#tempoReference != -1) { + const factor = this.#tempoReference / this.settings.tempo + this.channels.forEach(channel => { + channel.voices.forEach(voice => { + multiplyRecursive(voice.oscillator, factor) + }) + }) + multiplyRecursive(this.defaults.voice.oscillator, factor) + multiplyRecursive(this.defaults.am, factor) + multiplyRecursive(this.defaults.fm, factor) + multiplyRecursive(this.defaults.transpose, factor) + multiplyRecursive(this.defaults.gain, factor) + multiplyRecursive(this.defaults.em, factor) + multiplyRecursive(this.defaults.sx, factor) + } + + this.#tempoReference = this.settings.tempo + } + +} \ No newline at end of file diff --git a/dist/model/settings.js b/dist/model/settings.js new file mode 100644 index 0000000..9bb749f --- /dev/null +++ b/dist/model/settings.js @@ -0,0 +1,32 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class Settings extends Entity { + + #tempo = T(Number, 120 / 60 / 4) // time per beat + #tempoDriver = T(String, "bpm") + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get tempo() { + return this.#tempo + } + + set tempo(value) { + this.#tempo = value + } + + get tempoDriver() { + return this.#tempoDriver + } + + set tempoDriver(value) { + this.#tempoDriver = value + } + +} \ No newline at end of file diff --git a/dist/model/view.js b/dist/model/view.js new file mode 100644 index 0000000..32bf188 --- /dev/null +++ b/dist/model/view.js @@ -0,0 +1,43 @@ +import {T, O, A} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import Entity from "./entity.js" + +export default class View extends Entity { + + #name = T(String, randomName()) + #path = A(String, []) + #navigationCollapsed = false + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get path() { + return this.#path + } + + set path(value) { + this.#path = value + } + + get navigationCollapsed() { + return this.#navigationCollapsed + } + + set navigationCollapsed(value) { + this.#navigationCollapsed = value + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + +} \ No newline at end of file diff --git a/dist/model/voice.js b/dist/model/voice.js new file mode 100644 index 0000000..0775070 --- /dev/null +++ b/dist/model/voice.js @@ -0,0 +1,120 @@ +import {A, T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import Entity from "./entity.js" +import WaveSplineOscillator from "./wave-spline-oscillator.js" + +export default class Voice extends Entity { + static IDLE = "idle" + static TRIGGER_ATTACK = "trigger-attack" + static ATTACK = "attack" + static SUSTAIN = "sustain" + static TRIGGER_RELEASE = "trigger-release" + static RELEASE = "release" + static TRIGGER_DELETE = "trigger-delete" + static DELETE_RELEASE = "delete-release" + static DELETE = "delete" + + #oscillator = T(WaveSplineOscillator, {}) + + #on = T(Number, 0) + #off = T(Number, Number.MAX_SAFE_INTEGER) + + #gain = T(Number, 1) + + #attack = T(Number, 1) + #release = T(Number, 1) + #path = A(String, []) + + #name = T(String, randomName()) + + #bus = T(String, "main") + + #state = T(String, Voice.IDLE) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get oscillator() { + return this.#oscillator + } + + set oscillator(value) { + this.#oscillator = value + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get state() { + return this.#state + } + + set state(value) { + this.#state = value + } + + get on() { + return this.#on + } + + set on(value) { + this.#on = value + } + + get off() { + return this.#off + } + + set off(value) { + this.#off = value + } + + get attack() { + return this.#attack + } + + set attack(value) { + this.#attack = value + } + + get release() { + return this.#release + } + + set release(value) { + this.#release = value + } + + get path() { + return this.#path + } + + set path(value) { + this.#path = value + } + + get bus() { + return this.#bus + } + + set bus(value) { + this.#bus = value + } +} \ No newline at end of file diff --git a/dist/model/wave-spline-oscillator.js b/dist/model/wave-spline-oscillator.js new file mode 100644 index 0000000..2cdc65b --- /dev/null +++ b/dist/model/wave-spline-oscillator.js @@ -0,0 +1,140 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" +import WaveSpline from "./wave-spline.js" + +export default class WaveSplineOscillator extends Entity { + #length = T(Number, 1) + #lengthDriver = T(String, "frequency") + #tempoSync = T(Boolean, false) + #wave = T(WaveSpline, {}) + #phase = T(Number,0) + #phaseShift = T(Number, 0) + #fm = T(WaveSplineOscillator) + #fmRange = T(Number, 2) + #am = T(WaveSplineOscillator) + #em = T(WaveSplineOscillator) + #sx = T(WaveSplineOscillator) + #sy = T(WaveSplineOscillator) + #gain = T(WaveSplineOscillator) + #transpose = T(WaveSplineOscillator) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get length() { + return this.#length + } + + set length(value) { + this.#length = value + } + + get tempoSync() { + return this.#tempoSync + } + + set tempoSync(value) { + this.#tempoSync = value + } + + get wave() { + return this.#wave + } + + set wave(value) { + this.#wave = value + } + + get fm() { + return this.#fm + } + + set fm(value) { + this.#fm = value + } + + get fmRange() { + return this.#fmRange + } + + set fmRange(value) { + this.#fmRange = value + } + + get transpose() { + return this.#transpose + } + + set transpose(value) { + this.#transpose = value + } + + get am() { + return this.#am + } + + set am(value) { + this.#am = value + } + + get em() { + return this.#em + } + + set em(value) { + this.#em = value + } + + get sx() { + return this.#sx + } + + set sx(value) { + this.#sx = value + } + + get sy() { + return this.#sy + } + + set sy(value) { + this.#sy = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get phase() { + return this.#phase + } + + set phase(value) { + this.#phase = value + } + + get phaseShift() { + return this.#phaseShift + } + + set phaseShift(value) { + this.#phaseShift = value + } + + get lengthDriver() { + return this.#lengthDriver + } + + set lengthDriver(value) { + this.#lengthDriver = value + } + +} \ No newline at end of file diff --git a/dist/model/wave-spline-point.js b/dist/model/wave-spline-point.js new file mode 100644 index 0000000..a39bae4 --- /dev/null +++ b/dist/model/wave-spline-point.js @@ -0,0 +1,38 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class WaveSplinePoint extends Entity { + #x = T(Number, 0) + #y = T(Number, 0) + #e = T(Number, 1) + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get x() { + return this.#x + } + + set x(value) { + this.#x = value + } + + get y() { + return this.#y + } + + set y(value) { + this.#y = value + } + + get e() { + return this.#e + } + + set e(value) { + this.#e = value + } +} \ No newline at end of file diff --git a/dist/model/wave-spline.js b/dist/model/wave-spline.js new file mode 100644 index 0000000..c309288 --- /dev/null +++ b/dist/model/wave-spline.js @@ -0,0 +1,168 @@ +import { T, A } from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" +import Point from "./point.js" +import WaveSplinePoint from "./wave-spline-point.js" + +export default class WaveSpline extends Entity { + #e = T(Number, 1) + #points = A(WaveSplinePoint) + #quantizeX = T(Number, Number.MAX_SAFE_INTEGER) + #quantizeXThreshold = T(Number, -1) + #quantizeY = T(Number, Number.MAX_SAFE_INTEGER) + #quantizeYThreshold = T(Number, 0) + #gridX = T(Number, Number.MAX_SAFE_INTEGER) + #gridXThreshold = T(Number, 0) + #gridY = T(Number, Number.MAX_SAFE_INTEGER) + #gridYThreshold = T(Number, 0) + + #viewZoom = T(Number, 1) + #viewPosition = T(Number, 0) + + #transformCenter = T(Point, {x: 0.5, y: 0.5}) + #transformScale = T(Point, {x: 1, y: 1}) + #transformRange = T(Point, {x: 1.0, y: 1.0}) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get points() { + return this.#points + } + + set points(value) { + this.#points = value + } + + + get transformCenter() { + return this.#transformCenter + } + + set transformCenter(value) { + this.#transformCenter = value + } + + get transformScale() { + return this.#transformScale + } + + set transformScale(value) { + this.#transformScale = value + } + + get transformRange() { + return this.#transformRange + } + + set transformRange(value) { + this.#transformRange = value + } + + get e() { + return this.#e + } + + set e(value) { + this.#e = value + } + + get quantizeX() { + return this.#quantizeX + } + + set quantizeX(value) { + this.#quantizeX = value + } + + get quantizeXThreshold() { + return this.#quantizeXThreshold + } + + set quantizeXThreshold(value) { + this.#quantizeXThreshold = value + } + + get quantizeY() { + return this.#quantizeY + } + + set quantizeY(value) { + this.#quantizeY = value + } + + get quantizeYThreshold() { + return this.#quantizeYThreshold + } + + set quantizeYThreshold(value) { + this.#quantizeYThreshold = value + } + + get gridX() { + return this.#gridX + } + + set gridX(value) { + this.#gridX = value + } + + get gridXThreshold() { + return this.#gridXThreshold + } + + set gridXThreshold(value) { + this.#gridXThreshold = value + } + + get gridY() { + return this.#gridY + } + + set gridY(value) { + this.#gridY = value + } + + get gridYThreshold() { + return this.#gridYThreshold + } + + set gridYThreshold(value) { + this.#gridYThreshold = value + } + + get viewZoom() { + return this.#viewZoom + } + + set viewZoom(value) { + this.#viewZoom = value + } + + get viewPosition() { + return this.#viewPosition + } + + set viewPosition(value) { + this.#viewPosition = value + } + + insertPoint(value) { + this.points.push(value) + this.sort() + } + + removePoint(value) { + this.points.splice(this.#points.indexOf(value), 1) + } + + sort() { + this.points.sort((a, b)=>{ + if (a.x === b.x) return (a.id < b.id) ? -1 : 1 + return (a.x < b.x) ? -1 : 1 + }) + } +} \ No newline at end of file diff --git a/dist/music/beautify-frequency.js b/dist/music/beautify-frequency.js new file mode 100644 index 0000000..1cbd4c3 --- /dev/null +++ b/dist/music/beautify-frequency.js @@ -0,0 +1,27 @@ +export default function beautifyFrequency(frequency) { + /* + 1 Hz + 1.34 Hz + 100.31 Hz + 440 Hz + 1.3 kHz + 100.3 kHz + */ + let maxDigits = 4 + let value = frequency + let unit = "Hz" + if (value > 1e3) { + value /= 1e3 + unit = "kHz" + } + let fractionDigits = 1 + for (let e = 0; e < 3; e++) { + if (value <= Math.pow(10, e)) { + fractionDigits = maxDigits - e + break; + } + } + const scale = Math.pow(10, fractionDigits) + value = Math.round(value * scale) / scale + return { value, unit } +} \ No newline at end of file diff --git a/dist/music/beautify-time.js b/dist/music/beautify-time.js new file mode 100644 index 0000000..cac896c --- /dev/null +++ b/dist/music/beautify-time.js @@ -0,0 +1,26 @@ +export default function beautifyTime(seconds) { + let maxDigits = 3 + let value = seconds + let unit = "s" + + if (value < 1) { + value *= 1000 + unit = "ms" + } else if (value >= 60) { + value /= 60 + unit = "m" + } else if (value >= 60*60) { + value /= 60*60 + unit = "h" + } + let fractionDigits = 1 + for (let e = 0; e < 3; e++) { + if (value <= Math.pow(10, e)) { + fractionDigits = maxDigits - e + break; + } + } + const scale = Math.pow(10, fractionDigits) + value = Math.round(value * scale) / scale + return { value, unit } +} \ No newline at end of file diff --git a/dist/music/beautify-value.js b/dist/music/beautify-value.js new file mode 100644 index 0000000..3b30fe4 --- /dev/null +++ b/dist/music/beautify-value.js @@ -0,0 +1,25 @@ +export default function beautifyValue(frequency) { + let maxDigits = 4 + let value = frequency + let unit = "" + if (value > 1e3) { + value /= 1e3 + unit = "k" + } else if (value > 1e6) { + value /= 1e3 + unit = "M" + } else if (value > 1e9) { + value /= 1e3 + unit = "G" + } + let fractionDigits = 1 + for (let e = 0; e < 3; e++) { + if (value <= Math.pow(10, e)) { + fractionDigits = maxDigits - e + break; + } + } + const scale = Math.pow(10, fractionDigits) + value = Math.round(value * scale) / scale + return { value, unit } +} \ No newline at end of file diff --git a/dist/music/notes.js b/dist/music/notes.js new file mode 100644 index 0000000..d8d0657 --- /dev/null +++ b/dist/music/notes.js @@ -0,0 +1,120 @@ + +export class Note { + static LT = '<' + static GT = '>' + static CLOSE = '≈' + static EQ = '=' + static NONE = '!' + + frequency + precision + match + name + octave + color + index + + constructor({frequency = null, match = null, name = "", octave = null, color = null, precision=Note.NONE, index = 0} = {}) { + this.frequency = frequency + this.precision = precision + this.match = match + this.name = name + this.octave = octave + this.color = color + this.index = index + } +} + +export const ALTERNATIVE_NOTE_NAMES = (() => { + const greekAlphabet = 'αβγδεζηθικλμνξοπρςτυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ'.split('') + return [...greekAlphabet, ...greekAlphabet.map((value) => `${value}'`)] +})() + +export const PIANO_KEYS = (() => { + const from = 440 + const min = -4 + const zeroOctave = -5 + const max = 5 + const names = ["a", "a#", "b", "c", "c#", "d", "d#", "e", "f", "f#", "g", "g#"] + const colors = [0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1] + const octaveOffset = 9 + let arr = [] + let index = 0 + for (let octave = min; octave < max; octave++) { + let base = from * Math.pow(2, octave) + for (let note = 0; note < 12; note++) { + arr.push(new Note({ + match: base * Math.pow(2, note / 12), + name: names[note], + octave: Math.round(((octave - zeroOctave) * 12 + note - octaveOffset) / 12), + color: colors[note], + index + })) + index++ + } + } + return arr +})() + +export const OCTAVES = (() => { + const octaves = [] + let last = null + PIANO_KEYS.forEach(key => { + if (key.octave !== last) { + octaves.push(key) + last = key.octave + } + }) + return octaves +})() + +export const FREQUENCY_MAP = (() => { + const map = new Map() + PIANO_KEYS.forEach(key => { + map.set(Math.round(key.match * 100) / 100, key) + }) + return map +})() + +export function getOctave(frequency) { + if (frequency < OCTAVES[0].frequency) return null + for (let i = 0; i < OCTAVES.length; i++) { + if (frequency <= OCTAVES[i].frequency) return OCTAVES[i].octave - 1 + } + return null +} + +export function findClosestNote(frequency) { + let previousDelta = Number.MAX_SAFE_INTEGER + let previous + for (let i=0; i frequency) { + if (delta < previousDelta) return key + return previous + } + previousDelta = delta + previous = key + } + return previous +} + +export function getNoteByIndex(index) { + return new Note(PIANO_KEYS[index]) +} + +export function getNote(frequency) { + const closest = new Note(findClosestNote(frequency)) + closest.frequency = frequency + if (Math.abs(closest.match - frequency) < .001) { + closest.precision = Note.EQ + } else if (Math.abs(closest.match - frequency) < .5) { + closest.precision = Note.CLOSE + } else if (frequency > closest.match) { + closest.precision = Note.GT + } else if (frequency < closest.match) { + closest.precision = Note.LT + } + return closest +} diff --git a/dist/storage/db.js b/dist/storage/db.js new file mode 100644 index 0000000..c66b815 --- /dev/null +++ b/dist/storage/db.js @@ -0,0 +1,133 @@ +import clone from "../data/clone.js" +import Signal from "../glue/signal.js" +import generateTree from "../model/generate-tree.js" + +export default class DB { + + #db + #name + #version + + constructor(name, version) { + this.#name = name + this.#version = version + } + + open() { + return new Promise((resolve, reject)=>{ + const openRequest = indexedDB.open(this.#name, this.#version) + openRequest.onerror = (event) => { + reject('Error loading database.') + } + openRequest.onupgradeneeded = (event) => { + const db = event.target.result + const objectStore = db.createObjectStore("sessions", { keyPath: "id" }) + objectStore.createIndex("name", "name", { unique: false }) + objectStore.createIndex("changed", "changed", { unique: false }) + objectStore.createIndex("created", "created", { unique: false }) + } + openRequest.onsuccess = (event) => { + this.#db = openRequest.result + resolve(openRequest.result) + } + }) + } + + write(session) { + return new Promise((resolve, reject)=> { + const tx = this.#db.transaction(['sessions'], "readwrite") + const store = tx.objectStore("sessions") + const sessionObject = clone(session) + sessionObject.tree = generateTree(session) + sessionObject.changed = Date.now() + if (!sessionObject.created) sessionObject.created = Date.now() + store.put(sessionObject) + tx.oncomplete = () => { + resolve() + Signal.broadcast(this, {property: "sessions"}) + } + tx.onerror = () => { + reject(tx.error) + } + }) + } + + read(id) { + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions'); + const query = store.get(id) + query.onsuccess = () => { + resolve(query.result) + } + query.onerror = () => { + reject(tx.error) + } + + }) + } + + list() { + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions') + const index = store.index('created') + const cursor = index.openCursor(null, 'prev') + const result = [] + cursor.onsuccess = (event) => { + const currentCursor = event.target.result; + if (!currentCursor) return resolve(result) + const { id, name, tree, changed } = currentCursor.value + result.push({id, name, tree, changed}) + currentCursor.continue() + } + + cursor.onerror = (event) => { + reject() + } + + }) + } + + delete(id) { + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions'); + const request = store.delete(id) + tx.oncomplete = () => { + resolve() + Signal.broadcast(this, {property: "sessions"}) + } + tx.onerror = () => { + reject(tx.error) + } + + }) + } + + recent() { + + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions') + const index = store.index('changed') + const cursor = index.openCursor(null, 'prev') + + cursor.onsuccess = (event) => { + const currentCursor = event.target.result + if (currentCursor) resolve(currentCursor.value) + else resolve() + } + + cursor.onerror = (event) => { + reject() + } + + }) + } + + close() { + this.#db.close() + } + +} \ No newline at end of file diff --git a/dist/utils/camel-to-kebab.js b/dist/utils/camel-to-kebab.js new file mode 100644 index 0000000..44a6c1c --- /dev/null +++ b/dist/utils/camel-to-kebab.js @@ -0,0 +1,5 @@ +export default function camelToKebab(str) { + if (!str) return null + if (str === str.toUpperCase()) return str.toLowerCase() + return str.split(/(?=[A-Z])/).join('-').toLowerCase() +} \ No newline at end of file diff --git a/dist/utils/random-name.js b/dist/utils/random-name.js new file mode 100644 index 0000000..a66b57b --- /dev/null +++ b/dist/utils/random-name.js @@ -0,0 +1,35 @@ +import randomWord from "./random-word.js" + +function biasedRandomNumber(min, max, bias) { + const baseRandom = Math.random(); + const biasedRandom = Math.pow(baseRandom, 1/bias); + const range = max - min; + const scaledRandom = Math.floor(biasedRandom * range) + min; + + return Math.min(Math.max(scaledRandom, min), max); +} + +export default function randomName() { + let name = "" + const minChars = 5 + const maxChars = 13 + const minWordLength = 2 + const maxWordLength = 9 + const nameLen = biasedRandomNumber(minChars, maxChars, 2) + // Math.round(minChars + Math.random() * (maxChars-minChars)) + while (name.length < nameLen) { + if (name.length) name += " " + let wordLen + let available = (nameLen - name.length) + wordLen = biasedRandomNumber(minWordLength, maxWordLength, 3) + if (available < minWordLength*2+1) { + wordLen = available + } else if (available > wordLen) {// Math.round(minWordLength + Math.random() * (maxWordLength-minWordLength)) + wordLen = Math.min(available - minWordLength - 1, wordLen ) + } + const word = randomWord(wordLen) + name += word + } + name = name.split(" ").sort(()=>{return (Math.random()>0.5)?-1:1}).join(" ") + return name +} \ No newline at end of file diff --git a/dist/utils/random-pick.js b/dist/utils/random-pick.js new file mode 100644 index 0000000..564af35 --- /dev/null +++ b/dist/utils/random-pick.js @@ -0,0 +1,3 @@ +export default function randomPick(array) { + return array[Math.floor(Math.random() * array.length)] +} \ No newline at end of file diff --git a/dist/utils/random-word.js b/dist/utils/random-word.js new file mode 100644 index 0000000..f3d0bf0 --- /dev/null +++ b/dist/utils/random-word.js @@ -0,0 +1,38 @@ +import randomPick from "./random-pick.js"; + +const syllableType = { + "vowel":["ai", "ay", "ei", "ey", "oi", "oy", "ou", "au", "ea", "ee", "ie", "oo", "ue", "ui", "eu", "oa", "eo", "iu", "ae", "ui", "ie", "uo", "ey", "a", "e", "i", "o", "u", "y"], + "consonant": ["str", "scr", "sch", "spr", "spl", "thr", "shr", "squ", "sm", "sn", "sp", "st", "sk", "sl", "sw", "bl", "cl", "fl", "gl", "pl", "tl", "br", "cr", "dr", "fr", "gr", "pr", "tr", "ch", "sh", "th", "wh", "kn", "gn", "b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","z"], +} + +export default function randomWord(chars) { + let word = ""; + let lastType + + while (word.length < chars) { + let type + if (word.length == 0) { + type = randomPick(["vowel", "consonant"]) + } else if (lastType === "consonant") { + type = "vowel" + } else if (lastType === "vowel") { + type = "consonant" + } else { + type = "vowel" + } + + let available = chars-word.length + let maxSyllableLength = available + if (type === "consonant" && available == 3) maxSyllableLength = 2 + else if (type === "consonant" && available == 2) maxSyllableLength = 1 + const syllable = randomPick( + syllableType[type].filter((syllable)=>{ + return syllable.length <= maxSyllableLength + }) + ) + word += syllable + lastType = type + } + word = word.charAt(0).toUpperCase() + word.slice(1) + return word +} \ No newline at end of file diff --git a/dist/wave-spline/find-closest.js b/dist/wave-spline/find-closest.js new file mode 100644 index 0000000..025620d --- /dev/null +++ b/dist/wave-spline/find-closest.js @@ -0,0 +1,16 @@ +import calculateDistance from "../math/calculate-distance.js" + +export default function findClosest(p, points, weight = {x:1, y:1}) { + let best = Number.POSITIVE_INFINITY + let result = null + const len = points.length + for (let i = 0; i x ) { + b = i + break + } + a = i + } + return [points[a], points[b]] +} \ No newline at end of file diff --git a/dist/wave-spline/process-wave-spline-points.js b/dist/wave-spline/process-wave-spline-points.js new file mode 100644 index 0000000..3ea4db3 --- /dev/null +++ b/dist/wave-spline/process-wave-spline-points.js @@ -0,0 +1,39 @@ +import compareFloat from "../math/compare-float.js" +import transformWaveSplinePoint from "./transform-wave-spline-point.js" + +export default function processWaveSplinePoints(points, cx=.5, cy=.5, sx=1, sy=1, rx=1, ry=1) { + + const len = points.length + let out = [] + let point = {x: -1, y: 0, e: 0} + let x = -1 + let y = 0 + let e = 0 + let stackCount = 0 + let cur + for (let i = 0; i cx + rx) return point + return { + x: ((point.x-cx)*sx+cx), + y: ((point.y-cy)*sy+cy), + e: point.e + } +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..ee0d747 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1088 @@ +{ + "name": "mvls", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mvls", + "version": "1.0.0", + "license": "ISC", + "devDependencies": { + "chokidar": "^3.5.3", + "fs-extra": "^11.1.1", + "webpack": "^5.89.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.5.tgz", + "integrity": "sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.19", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", + "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@types/eslint": { + "version": "8.44.4", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.44.4.tgz", + "integrity": "sha512-lOzjyfY/D9QR4hY9oblZ76B90MYTB3RrQ4z2vBIJKj9ROCRqdkYl2gSUx1x1a4IWPjKJZLL4Aw1Zfay7eMnmnA==", + "dev": true, + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.5", + "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.5.tgz", + "integrity": "sha512-JNvhIEyxVW6EoMIFIvj93ZOywYFatlpu9deeH6eSx6PE3WHYvHaQtmHmQeNw7aA81bYGBPPQqdtBm6b1SsQMmA==", + "dev": true, + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.2.tgz", + "integrity": "sha512-VeiPZ9MMwXjO32/Xu7+OwflfmeoRwkE/qzndw42gGtgJwZopBnzy2gD//NN1+go1mADzkDcqf/KnFRSjTJ8xJA==", + "dev": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.13", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.13.tgz", + "integrity": "sha512-RbSSoHliUbnXj3ny0CNFOoxrIDV6SUGyStHsvDqosw6CkdPV8TtWGlfecuK4ToyMEAql6pzNxgCFKanovUzlgQ==", + "dev": true + }, + "node_modules/@types/node": { + "version": "20.8.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.6.tgz", + "integrity": "sha512-eWO4K2Ji70QzKUqRy6oyJWUeB7+g2cRagT3T/nxYibYcT4y2BDL8lqolRXjTHmkZCdJfIPaY73KbJAZmcryxTQ==", + "dev": true, + "dependencies": { + "undici-types": "~5.25.1" + } + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz", + "integrity": "sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==", + "dev": true, + "dependencies": { + "@webassemblyjs/helper-numbers": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz", + "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz", + "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.6.tgz", + "integrity": "sha512-z3nFzdcp1mb8nEOFFk8DrYLpHvhKC3grJD2ardfKOzmbmJvEf/tPIqCY+sNcwZIY8ZD7IkB2l7/pqhUhqm7hLA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz", + "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==", + "dev": true, + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.11.6", + "@webassemblyjs/helper-api-error": "1.11.6", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz", + "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.6.tgz", + "integrity": "sha512-LPpZbSOwTpEC2cgn4hTydySy1Ke+XEu+ETXuoyvuyezHO3Kjdu90KK95Sh9xTbmjrCsUwvWwCOQQNta37VrS9g==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-buffer": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/wasm-gen": "1.11.6" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz", + "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==", + "dev": true, + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz", + "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==", + "dev": true, + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz", + "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==", + "dev": true + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.6.tgz", + "integrity": "sha512-Ybn2I6fnfIGuCR+Faaz7YcvtBKxvoLV3Lebn1tM4o/IAJzmi9AWYIPWpyBfU8cC+JxAO57bk4+zdsTjJR+VTOw==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-buffer": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/helper-wasm-section": "1.11.6", + "@webassemblyjs/wasm-gen": "1.11.6", + "@webassemblyjs/wasm-opt": "1.11.6", + "@webassemblyjs/wasm-parser": "1.11.6", + "@webassemblyjs/wast-printer": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.6.tgz", + "integrity": "sha512-3XOqkZP/y6B4F0PBAXvI1/bky7GryoogUtfwExeP/v7Nzwo1QLcq5oQmpKlftZLbT+ERUOAZVQjuNVak6UXjPA==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.6.tgz", + "integrity": "sha512-cOrKuLRE7PCe6AsOVl7WasYf3wbSo4CeOk6PkrjS7g57MFfVUF9u6ysQBBODX0LdgSvQqRiGz3CXvIDKcPNy4g==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-buffer": "1.11.6", + "@webassemblyjs/wasm-gen": "1.11.6", + "@webassemblyjs/wasm-parser": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.6.tgz", + "integrity": "sha512-6ZwPeGzMJM3Dqp3hCsLgESxBGtT/OeCvCZ4TA1JUPYgmhAx38tTPR9JaKy0S5H3evQpO/h2uWs2j6Yc/fjkpTQ==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/helper-api-error": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.6.tgz", + "integrity": "sha512-JM7AhRcE+yW2GWYaKeHL5vt4xqee5N2WcezptmgyhNS+ScggqcT1OtXykhAb13Sn5Yas0j2uv9tHgrjwvzAP4A==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.6", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "node_modules/acorn": { + "version": "8.10.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", + "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-assertions": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz", + "integrity": "sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==", + "dev": true, + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "dev": true, + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.1.tgz", + "integrity": "sha512-FEVc202+2iuClEhZhrWy6ZiAcRLvNMyYcxZ8raemul1DYVOVdFsbqckWLdsixQZCpJlwe77Z3UTalE7jsjnKfQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "caniuse-lite": "^1.0.30001541", + "electron-to-chromium": "^1.4.535", + "node-releases": "^2.0.13", + "update-browserslist-db": "^1.0.13" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001549", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001549.tgz", + "integrity": "sha512-qRp48dPYSCYaP+KurZLhDYdVE+yEyht/3NlmcJgVQ2VMGt6JL36ndQ/7rgspdZsJuxDPFIo/OzBT2+GmIJ53BA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ] + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", + "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", + "dev": true, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/electron-to-chromium": { + "version": "1.4.556", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.556.tgz", + "integrity": "sha512-6RPN0hHfzDU8D56E72YkDvnLw5Cj2NMXZGg3UkgyoHxjVhG99KZpsKgBWMmTy0Ei89xwan+rbRsVB9yzATmYzQ==", + "dev": true + }, + "node_modules/enhanced-resolve": { + "version": "5.15.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz", + "integrity": "sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/es-module-lexer": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.3.1.tgz", + "integrity": "sha512-JUFAyicQV9mXc3YRxPnDlrfBKpqt6hUYzz9/boprUJHs4e4KVr3XwOF70doO6gwXUor6EWZJAyWAfKki84t20Q==", + "dev": true + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs-extra": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.1.1.tgz", + "integrity": "sha512-MGIE4HOvQCeUCzmlHs0vXpih4ysz4wg9qiSAu6cd42lVwPbTM1TjV7RusoyQqMmk/95gdQZX72u+YW+c3eEpFQ==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/loader-runner": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "dev": true, + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true + }, + "node_modules/node-releases": { + "version": "2.0.13", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", + "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==", + "dev": true + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/punycode": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", + "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/schema-utils": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", + "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.1.tgz", + "integrity": "sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w==", + "dev": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/terser": { + "version": "5.22.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.22.0.tgz", + "integrity": "sha512-hHZVLgRA2z4NWcN6aS5rQDc+7Dcy58HOf2zbYwmFcQ+ua3h6eEFf5lIDKTzbWwlazPyOZsFQO8V80/IjVNExEw==", + "dev": true, + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.3.9", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.9.tgz", + "integrity": "sha512-ZuXsqE07EcggTWQjXUj+Aot/OMcD0bMKGgF63f7UxYcu5/AJF53aIpK1YoP5xR9l6s/Hy2b+t1AM0bLNPRuhwA==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.17", + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.1", + "terser": "^5.16.8" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/undici-types": { + "version": "5.25.3", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.25.3.tgz", + "integrity": "sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA==", + "dev": true + }, + "node_modules/universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", + "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/watchpack": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz", + "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==", + "dev": true, + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack": { + "version": "5.89.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.89.0.tgz", + "integrity": "sha512-qyfIC10pOr70V+jkmud8tMfajraGCZMBWJtrmuBymQKCrLTRejBI8STDp1MCyZu/QTdZSeacCQYpYNQVOzX5kw==", + "dev": true, + "dependencies": { + "@types/eslint-scope": "^3.7.3", + "@types/estree": "^1.0.0", + "@webassemblyjs/ast": "^1.11.5", + "@webassemblyjs/wasm-edit": "^1.11.5", + "@webassemblyjs/wasm-parser": "^1.11.5", + "acorn": "^8.7.1", + "acorn-import-assertions": "^1.9.0", + "browserslist": "^4.14.5", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.15.0", + "es-module-lexer": "^1.2.1", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.9", + "json-parse-even-better-errors": "^2.3.1", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.2.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.3.7", + "watchpack": "^2.4.0", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-sources": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz", + "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", + "dev": true, + "engines": { + "node": ">=10.13.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..41a84da --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "mvls", + "version": "1.0.0", + "description": "", + "main": "wave-spline-processor.js", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "node scripts/build.js", + "serve": "npx http-server ./dist" + }, + "author": "", + "license": "ISC", + "devDependencies": { + "chokidar": "^3.5.3", + "fs-extra": "^11.1.1", + "webpack": "^5.89.0" + } +} diff --git a/scripts/build.js b/scripts/build.js new file mode 100644 index 0000000..3393e01 --- /dev/null +++ b/scripts/build.js @@ -0,0 +1,80 @@ +#!/usr/bin/env node + +import chokidar from "chokidar" +import fs from 'fs-extra' +import webpack from 'webpack' +import path from 'path' + +function bundleWorklet() { + return new Promise((resolve, reject)=>{ + webpack({ + entry: { + "wave-spline-processor": './src/audio/wave-spline-processor.js', + }, + output: { + path: path.resolve('./', 'dist/audio/'), + filename: '[name].js' + }, + optimization: { + minimize: false + } + }, (err, stats) => { + if (err || stats.hasErrors()) { + console.log(stats) + reject(err) + } else { + resolve() + } + }) + }) +} + +async function build() { + console.log("Build AWSM") + try { + console.info("Remove dir") + await fs.remove('./dist') + console.info("Copy files") + await fs.copy('./src', './dist') + console.info("Bundle Worklet") + await bundleWorklet() + console.info("Done") + } catch(e) { + console.error(e) + } +} + + +chokidar.watch([ + './src', + '../shared/model/src' + ]).on('all', (event, path) => { + triggerBuild() + // +}); + + +let buildTriggered = false +let changedWhileBuild = false +let timeout +function triggerBuild() { + if (buildTriggered) { + if (!timeout) changedWhileBuild = true + return + } + console.log("trigger build") + buildTriggered = true + changedWhileBuild = false + timeout = setTimeout(async ()=>{ + timeout = null + await build() + console.log("build complete") + buildTriggered = false + if (changedWhileBuild) { + console.log("retrigger") + triggerBuild() + } + },1000) + +} +triggerBuild() \ No newline at end of file diff --git a/src/audio/audio-metrics-analyzer.js b/src/audio/audio-metrics-analyzer.js new file mode 100644 index 0000000..8887a55 --- /dev/null +++ b/src/audio/audio-metrics-analyzer.js @@ -0,0 +1,45 @@ + +export default class AudioMetricsAnalyzer { + + #audioContext + #analyserNode + #audioMetrics + #source + #lastFrame = 0 + constructor(audioContext) { + this.#audioContext = audioContext + this.#analyserNode = this.#audioContext.createAnalyser() + this.#analyserNode.fftSize = 2048 + this.#analyserNode.smoothingTimeConstant = 0.8 + } + + connect(source) { + if (this.#source) this.#source.disconnect(this.#analyserNode) + this.#source = source + this.#source.connect(this.#analyserNode) + } + + update() { + const now = Date.now() + if (!this.#audioMetrics || this.#lastFrame >= now-10) return + this.#lastFrame = now + this.#analyserNode.getByteTimeDomainData(this.#audioMetrics.frame) + } + + set audioMetrics(value) { + this.#audioMetrics = value + this.#audioMetrics.frame = new Uint8Array(this.#analyserNode.frequencyBinCount) + this.#audioMetrics.callback = this.update.bind(this) + } + + get audioMetrics() { + return this.#audioMetrics + } + + destroy() { + this.#source.disconnect(this.#analyserNode) + this.#audioMetrics = null + this.#audioContext = null + this.#analyserNode = null + } +} \ No newline at end of file diff --git a/src/audio/audio-squeeze-processor.js b/src/audio/audio-squeeze-processor.js new file mode 100644 index 0000000..b16fc04 --- /dev/null +++ b/src/audio/audio-squeeze-processor.js @@ -0,0 +1,141 @@ +import interpolateLinear from "../math/interpolate-linear.js" + +class AudioSqueezeProcessor extends AudioWorkletProcessor { + static get parameterDescriptors() { + return [{ + name: 'threshold', // threshold (0-1 normalized) + defaultValue: 0.5, + minValue: 0.0, + maxValue: 1.0, + automationRate: "a-rate", + }, { + name: 'scale', // scale + defaultValue: 1, + minValue: 0, + maxValue: 10, + automationRate: "a-rate", + }, { + name: 'potential', // loudness factor + defaultValue: 0.0, + minValue: 0, + maxValue: 1, + automationRate: "a-rate", + }, { + name: 'inputs', + defaultValue: 0, + minValue: 0, + maxValue: 128, + automationRate: "k-rate", + }] + } + + #bufferIndex = 0 + + #targetPeak = 0 + #peak = 0 + #peakIncrement = 0 + #peakTime = 0 + + #buffer = new Float32Array(512) + #output = new Float32Array(128) + #delay = 512 + + constructor(...args) { + super(...args) + this.port.onmessage = (message) => { + if (message.data.type === "destroy") { + this.onDestroy() + } + } + } + + onDestroy() { + this.port.onmessage = null + this.port.close() + } + + process(inputs, outputs, parameters) { + for (let outputIndex = 0; outputIndex < outputs.length; outputIndex++) { + const output = outputs[outputIndex] + for (let channelIndex = 0; channelIndex < output.length; channelIndex++) { + const channel = output[channelIndex] + if (outputIndex == 0 && channelIndex == 0) { + if (channel.length != this.#buffer.length) { + this.#output = new Float32Array(channel.length) + } + if (this.#buffer.length != this.#delay) { + this.#buffer = new Float32Array(this.#delay) + } + } + for (let sample = 0; sample < channel.length; sample++) { + if (channelIndex == 0 && outputIndex == 0) { + + let amplitude = 0 + for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) { + const input = inputs[inputIndex] + if (input.length) amplitude += input[channelIndex][sample] + } + + this.#buffer[this.#bufferIndex] = amplitude + + let magnitude = Math.abs(amplitude) + + if (magnitude >= this.#targetPeak *.9) { + this.#peakTime = 0 + } + if (magnitude >= this.#targetPeak) { + this.#targetPeak = magnitude + } + this.#peakIncrement = (8 * this.#targetPeak) / this.#delay // min value to get from -peak to peak within delay + + if (this.#peak - this.#peakIncrement > this.#targetPeak) { + this.#peak -= this.#peakIncrement + } else if (this.#peak + this.#peakIncrement < this.#targetPeak) { + this.#peak += this.#peakIncrement + } else { + this.#peak = this.#targetPeak + } + + let liveAmplitude = this.#buffer[(this.#bufferIndex+1)%this.#buffer.length] || 0 + let liveMagnitude = Math.abs(liveAmplitude) + let liveSign = Math.sign(liveAmplitude) + const overdrive = parameters.potential.length>1?parameters.potential[sample]:parameters.potential[0] + const threshold = (parameters.threshold.length>1?parameters.threshold[sample]:parameters.threshold[0]) * .99 + const scale = parameters.scale.length>1?parameters.scale[sample]:parameters.scale[0] + let out = 0 + let scaledMax = Math.max( + threshold + (1-threshold) * scale, + threshold + (1-threshold) * .5 + ) + + if (this.#peak > 0) { + out = liveMagnitude / this.#peak + if (out > threshold) { + let rel = out - threshold + let scaledRel = rel * scale + out = threshold + interpolateLinear(rel, scaledRel, rel/(1-threshold)) + } + } + out /= scaledMax + if (this.#peak < 1) out = interpolateLinear(out * this.#peak, out, overdrive) + + this.#output[sample] = out * liveSign * .9999 + + if (this.#peakTime > this.#delay ) { + this.#targetPeak = this.#targetPeak * .99999 + } + + this.#bufferIndex = (this.#bufferIndex+1)%this.#buffer.length + this.#peakTime++ + + } + channel[sample] = this.#output[sample] + + + } + } + } + return true + } +} +registerProcessor("audio-squeeze-processor", AudioSqueezeProcessor); \ No newline at end of file diff --git a/src/audio/channel-manager.js b/src/audio/channel-manager.js new file mode 100644 index 0000000..60f0ea4 --- /dev/null +++ b/src/audio/channel-manager.js @@ -0,0 +1,190 @@ +import watch from "../glue/watch.js" +import unwatch from "../glue/unwatch.js" +import Channel from "../model/channel.js" +import VoiceManager from "./voice-manager.js" +import Dynamics from "../model/dynamics.js" +import Voice from "../model/voice.js" +import AudioMetricsAnalyzer from "./audio-metrics-analyzer.js" + +export default class ChannelManager { + #audioContext + #channel + #voiceMap = new Map() + #gainNode + #mix = 0 + #inputs + #potentialParam + #dynamics + #thresholdParam + #scaleParam + #channelGainChangeTime = 1/100 + #audioMetricsAnalyzer + #soloBus + #releaseTimeout + #potentialChangeTime = 1/10 + + constructor(audioContext, channel) { + this.#audioContext = audioContext + this.#gainNode = this.#audioContext.createGain() + this.#gainNode.gain.value = 0 + + this.#dynamics = new AudioWorkletNode(this.#audioContext, 'audio-squeeze-processor') + this.#inputs = this.#dynamics.parameters.get('inputs') + this.#potentialParam = this.#dynamics.parameters.get('potential') + this.#thresholdParam = this.#dynamics.parameters.get('threshold') + this.#scaleParam = this.#dynamics.parameters.get('scale') + this.#dynamics.connect(this.#gainNode) + + this.#audioMetricsAnalyzer = new AudioMetricsAnalyzer(this.#audioContext) + this.#audioMetricsAnalyzer.connect(this.#gainNode) + + watch(this, "channel", this.#onChannelChange.bind(this)) + if (channel) this.channel = channel + + } + + set channel(value) { + this.#channel = value + this.#audioMetricsAnalyzer.audioMetrics = this.#channel.audioMetrics + this.#updateDynamics() + this.#update() + } + + get channel() { + return this.#channel + } + + set mix(value) { + this.#mix = value + this.#update() + } + + get mix() { + return this.#mix + } + + get audioMetrics() { + return this.#audioMetricsAnalyzer + } + + pause() { + this.#voiceMap.forEach((voiceManager)=>{ + voiceManager.pause() + }) + } + + play() { + this.#voiceMap.forEach((voiceManager)=>{ + voiceManager.play() + }) + } + + connect(destination) { + this.#gainNode.connect(destination) + } + + set soloBus(value) { + this.#soloBus = value + this.#voiceMap.forEach((voiceManager) => { + voiceManager.soloBus = this.#soloBus + }) + } + + get soloBus() { + return this.#soloBus + } + + sync() { + this.#voiceMap.forEach((voiceManager) => { + voiceManager.sync() + }) + } + + zeroAll(id, found=false) { + if (this.#channel.id === id) found = true + this.#voiceMap.forEach((voiceManager) => { + voiceManager.zeroAll(id, found) + }) + } + + #onChannelChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + ) { + this.#updateDynamics() + + } else if (signal.path.length == 1){ + this.#update() + } + } + + #updateDynamics() { + this.#thresholdParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#thresholdParam.setValueAtTime(this.#thresholdParam.value, this.#audioContext.currentTime); + this.#thresholdParam.linearRampToValueAtTime( this.#channel.dynamics.threshold, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#scaleParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#scaleParam.setValueAtTime(this.#scaleParam.value, this.#audioContext.currentTime); + this.#scaleParam.linearRampToValueAtTime( this.#channel.dynamics.scale, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#potentialParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#potentialParam.setValueAtTime(this.#potentialParam.value, this.#audioContext.currentTime); + this.#potentialParam.linearRampToValueAtTime( this.#channel.dynamics.potential, this.#audioContext.currentTime + this.#potentialChangeTime); + + } + + #onReleaseTimeout() { + if (this.#channel.state === Channel.RELEASE) { + this.#channel.state = Channel.DELETE + } + } + + #update() { + this.#inputs.setValueAtTime(this.#channel.voices.length, this.#audioContext.currentTime) + if (this.#channel.state === Channel.ACTIVE) { + clearTimeout(this.#releaseTimeout) + this.#channel.voices.forEach(voice => { + if (voice.state === Voice.DELETE) { + if (this.#voiceMap.has(voice.id)) { + let voiceManager = this.#voiceMap.get(voice.id) + voiceManager.destroy() + this.#voiceMap.delete(voice.id) + } + } else { + if (!this.#voiceMap.has(voice.id)) { + const voiceManager = new VoiceManager(this.#audioContext, voice) + voiceManager.connect(this.#dynamics) + voiceManager.soloBus = this.#soloBus + this.#voiceMap.set(voice.id, voiceManager) + } + } + }) + let gainMultiplier = 1 + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime) + this.#gainNode.gain.linearRampToValueAtTime( + this.#channel.gain * gainMultiplier * this.#mix, + this.#audioContext.currentTime + this.#channelGainChangeTime + ) + } else if (this.#channel.state === Channel.TRIGGER_RELEASE) { + clearTimeout(this.#releaseTimeout) + this.#channel.state = Channel.RELEASE + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime) + this.#gainNode.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#channel.release) + this.#releaseTimeout = setTimeout(()=>{this.#onReleaseTimeout()}, this.channel.release * 1000) + } + } + + destroy() { + unwatch(this, "channel") + this.#voiceMap.forEach((voiceManager, key) => { + voiceManager.destroy() + }) + this.#voiceMap = null + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.disconnect() + this.#audioContext = null + this.#channel = null + } +} \ No newline at end of file diff --git a/src/audio/session-manager.js b/src/audio/session-manager.js new file mode 100644 index 0000000..f03885a --- /dev/null +++ b/src/audio/session-manager.js @@ -0,0 +1,282 @@ +import watch from "../glue/watch.js" +import calculatePoleValue from "../math/calculate-pole-value.js" +import Channel from "../model/channel.js" +import Dynamics from "../model/dynamics.js" +import Session from "../model/session.js" +import AudioMetricsAnalyzer from "./audio-metrics-analyzer.js" +import ChannelManager from "./channel-manager.js" + +export default class SessionManager { + #audioContext + #session = new Session() + #channels = [] + #ready = false + #scheduled = false + #gainNode + #masterNode + #channelMap = new Map() + #dynamicLimit + #thresholdParam + #scaleParam + #potentialParam + #audioMetricsAnalyzer + #outNode + #powerUpTime = 2 + #syncInterval + #syncRate = 1000/30 + #soloBus + #mainBus + constructor(session) { + watch(this, "session", this.#onSessionChange.bind(this)) + if (session) this.session = session + } + + + async inititialize() { + this.#audioContext = new AudioContext() + await this.#audioContext.audioWorklet.addModule(`audio/wave-spline-processor.js?a=${Math.random()}`).catch(console.error) + await this.#audioContext.audioWorklet.addModule(`audio/audio-squeeze-processor.js?a=${Math.random()}`).catch(console.error) + + // preglow to remove initial latency + const wsp = new AudioWorkletNode(this.#audioContext, 'wave-spline-processor') + const asp = new AudioWorkletNode(this.#audioContext, 'audio-squeeze-processor') + + + + this.#dynamicLimit = new AudioWorkletNode(this.#audioContext, 'audio-squeeze-processor') + this.#thresholdParam = this.#dynamicLimit.parameters.get('threshold') + this.#scaleParam = this.#dynamicLimit.parameters.get('scale') + this.#potentialParam = this.#dynamicLimit.parameters.get('potential') + + this.#gainNode = this.#audioContext.createGain() + this.#gainNode.gain.value = 0 + + this.#masterNode = this.#audioContext.createGain() + this.#masterNode.gain.value = 0 + + this.#outNode = this.#audioContext.createGain() + this.#outNode.gain.value = 0 + + + this.#mainBus = this.#audioContext.createGain() + this.#mainBus.connect(this.#gainNode) + + this.#soloBus = this.#audioContext.createGain() + this.#soloBus.connect(this.#gainNode) + + this.#gainNode.connect(this.#audioContext.destination) + + this.#dynamicLimit.connect(this.#masterNode) + this.#masterNode.connect(this.#outNode) + + setTimeout(()=>{ + this.#outNode.connect(this.#mainBus) + + this.#powerUp() + }, 1000) + + this.#audioMetricsAnalyzer = new AudioMetricsAnalyzer(this.#audioContext) + this.#audioMetricsAnalyzer.connect(this.#masterNode) + + this.#ready = true + if (this.#scheduled) { + this.#update() + this.#updatePotential() + this.#updateDynamics() + } + } + + set session(value) { + this.#session = value + if (this.#session) { + this.#audioMetricsAnalyzer.audioMetrics = this.#session.audioMetrics + this.solo(this.#session.solo) + } + this.#update() + this.#updatePotential() + this.#updateDynamics() + } + + #powerUp() { + + this.#syncInterval = setInterval(()=>{ + this.sync() + }, this.#syncRate) + this.#outNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#outNode.gain.setValueAtTime(this.#outNode.gain.value, this.#audioContext.currentTime); + this.#outNode.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#powerUpTime) + } + + sync() { + this.#channelMap.forEach((channelManager)=>{ + channelManager.sync() + }) + } + + get session() { + return this.#session + } + + get audioContext() { + return this.#audioContext + } + + get audioMetrics() { + return this.#audioMetricsAnalyzer + } + + #onSessionChange(signal) { + if (signal.path[0].property === "solo") { + this.solo(this.#session.solo) + } else if ( + signal.path[0].origin instanceof Dynamics + ) { + this.#updateDynamics() + + } else if (signal.path.length <= 2){ + this.#update() + this.#updatePotential() + } + } + + #soloTime = 1/100 + + solo(id) { + if (id) { + this.#mainBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#mainBus.gain.setValueAtTime(this.#mainBus.gain.value, this.#audioContext.currentTime); + this.#mainBus.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#soloTime) + + this.#soloBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#soloBus.gain.setValueAtTime(this.#soloBus.gain.value, this.#audioContext.currentTime); + this.#soloBus.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#soloTime) + } else { + this.#soloBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#soloBus.gain.setValueAtTime(this.#soloBus.gain.value, this.#audioContext.currentTime); + this.#soloBus.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#soloTime) + + this.#mainBus.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#mainBus.gain.setValueAtTime(this.#mainBus.gain.value, this.#audioContext.currentTime); + this.#mainBus.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#soloTime) + } + } + + stopAll() { + if (!this.#ready) return Promise.resolve() + return new Promise((resolve, reject)=> { + this.#ready = false + this.#scheduled = false + this.#masterNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#masterNode.gain.setValueAtTime(this.#masterNode.gain.value, this.#audioContext.currentTime); + this.#masterNode.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#playPauseTime) + setTimeout(()=>{ + for (let [id, channelManager] of this.#channelMap) { + channelManager.destroy() + this.#channelMap.delete(id) + } + this.#ready = true + resolve() + if (this.#scheduled) this.#update() + }, this.#playPauseTime * 1000 ) + }) + + } + + #updateDynamics() { + if (!this.#ready) return this.#scheduled = true + if (!this.#session) return + + this.#thresholdParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#thresholdParam.setValueAtTime(this.#thresholdParam.value, this.#audioContext.currentTime); + this.#thresholdParam.linearRampToValueAtTime( this.#session.dynamics.threshold, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#scaleParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#scaleParam.setValueAtTime(this.#scaleParam.value, this.#audioContext.currentTime); + this.#scaleParam.linearRampToValueAtTime( this.#session.dynamics.scale, this.#audioContext.currentTime + this.#potentialChangeTime); + + this.#potentialParam.cancelScheduledValues(this.#audioContext.currentTime); + this.#potentialParam.setValueAtTime(this.#potentialParam.value, this.#audioContext.currentTime); + this.#potentialParam.linearRampToValueAtTime( this.#session.dynamics.potential, this.#audioContext.currentTime + this.#potentialChangeTime); + + } + + #playPauseTime = 1/10 + #potentialChangeTime = 1/10 + #playPauseTimeout + + + + #update() { + if (!this.#ready) return this.#scheduled = true + if (!this.#session) return + if (this.#session.state === Session.TRIGGER_PLAY) { + clearTimeout(this.#playPauseTimeout) + this.#session.state = Session.PLAY + this.#channelMap.forEach((channelManager)=>{ + channelManager.play() + }) + this.#masterNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#masterNode.gain.setValueAtTime(this.#masterNode.gain.value, this.#audioContext.currentTime) + this.#masterNode.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#playPauseTime) + this.#playPauseTimeout = setTimeout(()=>{ + this.#session.state = Session.PLAYING + }, this.#playPauseTime * 1000) + } else if (this.#session.state === Session.TRIGGER_PAUSE) { + clearTimeout(this.#playPauseTimeout) + this.#session.state = Session.PAUSE + this.#masterNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#masterNode.gain.setValueAtTime(this.#masterNode.gain.value, this.#audioContext.currentTime); + this.#masterNode.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#playPauseTime) + + this.#playPauseTimeout = setTimeout(()=>{ + this.#channelMap.forEach((channelManager)=>{ + channelManager.pause() + }) + this.#session.state = Session.PAUSED + }, this.#playPauseTime * 1000) + + } + this.#session.channels.forEach(channel => { + if (channel.state === Channel.DELETE) { + if (this.#channelMap.has(channel.id)) { + let channelManager = this.#channelMap.get(channel.id) + channelManager.destroy() + this.#channelMap.delete(channel.id) + } + } else { + if (!this.#channelMap.has(channel.id)) { + let channelManager = new ChannelManager(this.#audioContext, channel) + channelManager.connect(this.#dynamicLimit) + channelManager.soloBus = this.#soloBus + this.#channelMap.set(channel.id, channelManager) + } + } + + }) + for (let i = 0; i{ + channelManager.zeroAll(id, found) + }) + } + + #updatePotential() { + if (!this.#ready) return this.#scheduled = true + if (!this.#session) return + let potentialFactor = 1 + + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime); + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime); + this.#gainNode.gain.linearRampToValueAtTime( this.#session.main * potentialFactor, this.#audioContext.currentTime + this.#potentialChangeTime); + + + } +} \ No newline at end of file diff --git a/src/audio/voice-manager.js b/src/audio/voice-manager.js new file mode 100644 index 0000000..2da8c2b --- /dev/null +++ b/src/audio/voice-manager.js @@ -0,0 +1,206 @@ +import clone from "../data/clone.js" +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Voice from "../model/voice.js" +import syncVoice from "../wave-spline/sync-voice.js" + +export default class VoiceManager { + #audioContext + #voice + #processor + #gainNode + #envelope + #envelopeTimeout + #gainChangeTime = 1/100 + #soloBus + #outBus + #soloConnected = false + + constructor(audioContext, voice) { + this.#audioContext = audioContext + this.#gainNode = this.#audioContext.createGain() + this.#gainNode.gain.value = 0 + this.#envelope = this.#audioContext.createGain() + this.#envelope.gain.value = 0 + this.#processor = new AudioWorkletNode(this.#audioContext, 'wave-spline-processor') + this.#processor.port.onmessage = (msg) => { + if (msg.data.type === "sync") { + syncVoice(this.voice, msg.data.voice) + } + } + + this.#processor.connect(this.#gainNode) + this.#gainNode.connect(this.#envelope) + + watch(this, "voice", this.#onVoiceChange.bind(this)) + if (voice) this.voice = voice + + } + + #onVoiceChange(signal) { + if (signal.path[0].property === "bus") { + this.#updateBus() + } else if (signal.path[0].property === "state") { + this.#updateState() + } else if (signal.path[0].origin === this.voice && signal.path[0].property === "gain") { + this.#updateGain() + } else if ( + signal.path[0].property !== "phase" + && signal.path[0].property !== "name" + && signal.path[0].property !== "lengthDriver" + && signal.path[0].property !== "gridX" + && signal.path[0].property !== "gridY" + && signal.path[0].property !== "viewZoom" + && signal.path[0].property !== "viewPosition" + ) { + this.#update() + } + } + + set voice(value) { + this.#voice = value + this.#updateBus() + this.#updateState() + this.#updateGain() + this.#update() + } + + get voice() { + return this.#voice + } + + pause() { + this.#processor.port.postMessage({ + type: "pause" + }) + } + + play() { + this.#processor.port.postMessage({ + type: "play" + }) + } + + sync() { + this.#processor.port.postMessage({ + type: "sync" + }) + } + + zeroAll(id, found=false) { + if (this.#voice.id === id) found = true + let updateRequired = false + const zeroRecursive = (osc, id, found=false) => { + if (osc.id === id) found = true + if (found) { + updateRequired = true + osc.phase = 0 + } + if (osc.fm) zeroRecursive(osc.fm, id, found) + if (osc.am) zeroRecursive(osc.am, id, found) + if (osc.em) zeroRecursive(osc.em, id, found) + if (osc.sx) zeroRecursive(osc.sx, id, found) + if (osc.sy) zeroRecursive(osc.sy, id, found) + if (osc.gain) zeroRecursive(osc.gain, id, found) + if (osc.transpose) zeroRecursive(osc.transpose, id, found) + } + zeroRecursive(this.#voice.oscillator, id, found) + if (updateRequired) this.#update(false) + } + + connect(destination) { + this.#outBus = destination + this.#envelope.connect(this.#outBus) + } + + set soloBus(value) { + this.#soloBus = value + this.#updateBus() + } + + get soloBus() { + return this.#soloBus + } + + #onEnvelopeTimeout() { + if (!this.#voice) return + if (this.#voice.state === Voice.RELEASE) { + this.#voice.state = Voice.IDLE + } else if (this.#voice.state === Voice.DELETE_RELEASE) { + this.#voice.state = Voice.DELETE + } else if (this.#voice.state === Voice.ATTACK) { + this.#voice.state = Voice.SUSTAIN + } + this.#envelopeTimeout = null + } + + #updateBus() { + if (this.#voice && this.#voice.bus === "main" && this.#outBus) { + if (this.#soloConnected) { + this.#envelope.disconnect(this.#soloBus) + this.#soloConnected = false + } + } else if (this.#voice && this.#voice.bus === "solo" && this.#soloBus) { + if (!this.#soloConnected) { + this.#envelope.connect(this.#soloBus) + this.#soloConnected = true + } + } + } + + #updateState() { + + if (this.#voice.state === Voice.TRIGGER_ATTACK) { + clearTimeout(this.#envelopeTimeout) + this.#voice.state = Voice.ATTACK + this.#envelope.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#envelope.gain.setValueAtTime(this.#envelope.gain.value, this.#audioContext.currentTime) + this.#envelope.gain.linearRampToValueAtTime(1, this.#audioContext.currentTime + this.#voice.attack) + this.#envelopeTimeout = setTimeout(()=>{this.#onEnvelopeTimeout()}, this.#voice.attack * 1000) + } else if (this.#voice.state === Voice.TRIGGER_RELEASE) { + clearTimeout(this.#envelopeTimeout) + this.#voice.state = Voice.RELEASE + this.#envelope.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#envelope.gain.setValueAtTime(this.#envelope.gain.value, this.#audioContext.currentTime) + this.#envelope.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#voice.release) + this.#envelopeTimeout = setTimeout(()=>{this.#onEnvelopeTimeout()}, this.#voice.release * 1000) + } else if (this.#voice.state === Voice.TRIGGER_DELETE) { + clearTimeout(this.#envelopeTimeout) + this.#voice.state = Voice.DELETE_RELEASE + this.#envelope.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#envelope.gain.setValueAtTime(this.#envelope.gain.value, this.#audioContext.currentTime) + this.#envelope.gain.linearRampToValueAtTime(0, this.#audioContext.currentTime + this.#voice.release) + this.#envelopeTimeout = setTimeout(()=>{this.#onEnvelopeTimeout()}, this.#voice.release * 1000) + } + } + + #updateGain() { + this.#gainNode.gain.cancelScheduledValues(this.#audioContext.currentTime) + this.#gainNode.gain.setValueAtTime(this.#gainNode.gain.value, this.#audioContext.currentTime) + this.#gainNode.gain.linearRampToValueAtTime(this.#voice.gain, this.#audioContext.currentTime + this.#gainChangeTime) + } + + #update(sync = true) { + this.#processor.port.postMessage({ + type: "voice", + voice: clone(this.#voice), + sync + }) + + + } + + destroy() { + unwatch(this, "voice") + this.#voice = null + this.#processor.port.postMessage({ + type: "destroy" + }) + + this.#processor.port.close() + this.#processor.disconnect() + this.#processor = null + this.#audioContext = null + + } +} \ No newline at end of file diff --git a/src/audio/wave-spline-processor.js b/src/audio/wave-spline-processor.js new file mode 100644 index 0000000..2b2f10a --- /dev/null +++ b/src/audio/wave-spline-processor.js @@ -0,0 +1,99 @@ + + +import interpolateLinear from "../math/interpolate-linear.js" +import solveVoice from "../wave-spline/solve-voice.js" +import syncVoice from "../wave-spline/sync-voice.js" + +class WaveSplineProcessor extends AudioWorkletProcessor { + + #voices = [] + #buffer = new Float32Array(128) + #maxTransitionTime = 1/60 + #transition = 0 + #keepAlive = true + #play = true + + constructor(...args) { + super(...args) + this.port.onmessage = (message) => { + if (message.data.type === "voice") { + this.onVoiceData(message.data.voice, message.data.sync) + } else if (message.data.type === "update") { + this.onVoiceUpdate(message.data.voice) + } else if (message.data.type === "destroy") { + this.onDestroy() + } else if (message.data.type === "sync") { + this.port.postMessage({type: "sync", voice: this.#voices[this.#voices.length-1]}) + } else if (message.data.type === "play") { + this.#play = true + } else if (message.data.type === "pause") { + this.#play = false + } + } + + } + + onVoiceData(voice, sync) { + if (this.#voices.length>2)this.#voices.pop() + if (sync && this.#voices.length) syncVoice(voice, this.#voices[this.#voices.length-1]) + this.#voices.push(voice) + } + + onVoiceUpdate(value) { + this.#voices.forEach((voice=>{ + Object.assign(voice, value) + })) + } + + onDestroy() { + this.port.onmessage = null + this.port.close() + this.#voices = [] + this.#transition = 0 + this.#keepAlive = false + } + + process(inputs, outputs, parameters) { + for (let outputIndex = 0; outputIndex < outputs.length; outputIndex++) { + const output = outputs[outputIndex] + for (let channelIndex = 0; channelIndex < output.length; channelIndex++) { + const channel = output[channelIndex] + if (outputIndex == 0 && channelIndex == 0 && channel.length != this.#buffer.length) this.#buffer = new Float32Array(channel.length) + for (let frame = 0; frame < channel.length; frame++) { + if (channelIndex == 0 && outputIndex == 0) { + let val = 0 + if (this.#play) { + if (this.#voices.length == 1) { + val = solveVoice(sampleRate, this.#voices[0]) + + } else if (this.#voices.length >= 2) { + const transitionFrames = Math.min(this.#maxTransitionTime, this.#voices[0].oscillator.length) * sampleRate + const q = this.#transition / transitionFrames + val = interpolateLinear( + solveVoice(sampleRate, this.#voices[0]), + solveVoice(sampleRate, this.#voices[1]), + q + ) + if (this.#voices.length >= 3) { + solveVoice(sampleRate, this.#voices[2]) + } + this.#transition++ + if (this.#transition >= transitionFrames) { + this.#voices.shift() + this.#transition = 0 + } + } + } + + this.#buffer[frame] = val + } + channel[frame] = this.#buffer[frame] + + } + } + } + + return this.#keepAlive + } +} +registerProcessor("wave-spline-processor", WaveSplineProcessor); \ No newline at end of file diff --git a/src/color/hsl-to-rgb.js b/src/color/hsl-to-rgb.js new file mode 100644 index 0000000..e8c58ff --- /dev/null +++ b/src/color/hsl-to-rgb.js @@ -0,0 +1,10 @@ +/* +Based on https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion +posted by Kamil Kiełczewski +input: h as an angle in [0,360] and s,l in [0,1] - output: r,g,b in [0,1] +*/ +export default function hslToRgb({h = 0, s = 0, l = 0} = {}) { + const a = s*Math.min(l,1-l) + const f = (n,k=(n+h/30)%12) => l - a * Math.max(Math.min(k-3,9-k,1),-1) + return {r: f(0), g: f(8), b: f(4)} +} \ No newline at end of file diff --git a/src/color/hsv-to-rgb.js b/src/color/hsv-to-rgb.js new file mode 100644 index 0000000..cdc90b8 --- /dev/null +++ b/src/color/hsv-to-rgb.js @@ -0,0 +1,9 @@ +/* +Based on https://stackoverflow.com/questions/17242144/javascript-convert-hsb-hsv-color-to-rgb-accurately/54024653#54024653 +posted by Kamil Kiełczewski +input: h in [0,360] and s,v in [0,1] - output: r,g,b in [0,1] +*/ +export default function hsvToRgb({h = 0, s = 0, v = 0} = {}) { + const f = (n,k=(n+h/60)%6) => v - v * s * Math.max(0, Math.min(k, 4 - k, 1)) + return {r: f(5), g: f(3), b: f(1)}; +} \ No newline at end of file diff --git a/src/color/rgb-to-css.js b/src/color/rgb-to-css.js new file mode 100644 index 0000000..955ff00 --- /dev/null +++ b/src/color/rgb-to-css.js @@ -0,0 +1,3 @@ +export default function rgbToCss({r = 0, g = 0, b = 0} = {}) { + return `rgb(${r*0xFF|0}, ${g*0xFF|0}, ${b*0xFF|0}, ${Math.max(0, Math.min(1, a))})` +} \ No newline at end of file diff --git a/src/color/rgb-to-hsl.js b/src/color/rgb-to-hsl.js new file mode 100644 index 0000000..eeb2601 --- /dev/null +++ b/src/color/rgb-to-hsl.js @@ -0,0 +1,12 @@ +/* +Based on https://stackoverflow.com/questions/2348597/why-doesnt-this-javascript-rgb-to-hsl-code-work/54071699#54071699 +posted by Kamil Kiełczewski +input: r,g,b in [0,1], out: h in [0,360) and s,l in [0,1] +*/ +export default function rgbToHsl({r = 0, g = 0, b = 0} = {}) { + const v = Math.max(r,g,b) + const c = v - Math.min(r,g,b) + const f = (1-Math.abs(v+v-c-1)) + const h = c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)) + return {h:60*(h<0?h+6:h), s: f ? c/f : 0, l: (v+v-c)/2} +} \ No newline at end of file diff --git a/src/color/rgb-to-hsv.js b/src/color/rgb-to-hsv.js new file mode 100644 index 0000000..68e76d5 --- /dev/null +++ b/src/color/rgb-to-hsv.js @@ -0,0 +1,11 @@ +/* +Based on https://stackoverflow.com/questions/8022885/rgb-to-hsv-color-in-javascript/54070620#54070620 +posted by Kamil Kiełczewski +input: r,g,b in [0,1], out: h in [0,360) and s,v in [0,1] +*/ +export default function rgbToHsv({r = 0, g = 0, b = 0} = {}) { + const v = Math.max(r,g,b) + const c = v - Math.min(r,g,b) + let h = c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)); + return {h: 60*(h<0?h+6:h), s: v&&c/v, v} + } \ No newline at end of file diff --git a/src/color/rgba-to-css.js b/src/color/rgba-to-css.js new file mode 100644 index 0000000..72bdc93 --- /dev/null +++ b/src/color/rgba-to-css.js @@ -0,0 +1,3 @@ +export default function rgbaToCss({r = 0, g = 0, b = 0, a = 1} = {}) { + return `rgba(${r*0xFF|0}, ${g*0xFF|0}, ${b*0xFF|0}, ${Math.max(0, Math.min(1, a))})` +} \ No newline at end of file diff --git a/src/component/awsm.css b/src/component/awsm.css new file mode 100644 index 0000000..84a85f0 --- /dev/null +++ b/src/component/awsm.css @@ -0,0 +1,20 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex: 1; + flex-direction: column; +} +.views { + display: flex; + overflow: hidden; + flex: 1; +} + +awsm-layout-manager { + flex: 1; +} \ No newline at end of file diff --git a/src/component/awsm.js b/src/component/awsm.js new file mode 100644 index 0000000..113ad50 --- /dev/null +++ b/src/component/awsm.js @@ -0,0 +1,334 @@ +/** + * AWSM - AwesomeWaveSplineMachine MKII. EcmaScript software synthesizer. + * Copyright (C) 2024 C. Nicholas Schreiber + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import Keyboard from './keyboard.js' +import Component from "./component.js" +import SessionManager from '../audio/session-manager.js' +import Session from '../model/session.js' +import LayoutManager from './layout-manager.js' +import KeyboardGroup from './keyboard-group.js' +import Channel from '../model/channel.js' +import Voice from '../model/voice.js' +import DB from '../storage/db.js' +import watch from '../glue/watch.js' +import DatabaseSessionList from './database-session-list.js' +import clone from '../data/clone.js' +import resetState from '../model/reset-state.js' +import SplashScreen from './splash-screen.js' +import SessionEditor from './session-editor.js' +import defaultSession from '../model/default-session.js' + + +const downloadJSON = (filename, data) => { + const blob = new Blob([JSON.stringify(data, null, 2)], { type: "text/json" }) + const link = document.createElement("a") + + link.download = `${filename.toLowerCase().replace(/\s+/g,'_')}.json` + link.href = window.URL.createObjectURL(blob) + link.dataset.downloadurl = ["text/json", link.download, link.href].join(":") + + const evt = new MouseEvent("click", { + view: window, + bubbles: true, + cancelable: true, + }); + + link.dispatchEvent(evt) + link.remove() +} + +export default class AwesomeWaveSplineMachine extends Component { + + static CHANGE = 'change' + static style = 'component/awsm.css' + + #views = document.createElement('div') + #session + #sessionManager = new SessionManager() + + #sessionEditor = LayoutManager.create() + #keyboard = KeyboardGroup.create() + #splashScreen = SplashScreen.create() + + #db = new DB("awsm", 1) + + #saveDelay = 1000 + #saveTriggered = false + #saveReady = true + + constructor() { + super() + console.group("AWSM - AwesomeWaveSplineMachine MKII") + console.log("EcmaScript software synthesizer.") + console.log("Copyright (C) 2024 C. Nicholas Schreiber") + console.log("This program comes with ABSOLUTELY NO WARRANTY") + console.log("This is free software, and you are welcome to redistribute it under certain conditions") + console.groupEnd() + + this.intitialized = false + this.#views.classList.add("views") + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + + async #init() { + + await this.appendStyleLink(AwesomeWaveSplineMachine.style) + this.shadowRoot.append(this.#splashScreen) + + this.#splashScreen.addEventListener(SplashScreen.DISMISS, this.binding(this.#onSplashScreenDismiss)) + + this.shadowRoot.addEventListener("drop", this.binding(this.#onDrop)) + this.shadowRoot.addEventListener("dragover", this.binding(this.#onDragOver)) + + this.intitialized = true + + } + + #onDragOver(ev) { + ev.preventDefault(); + } + + #onDrop(ev) { + const insert = async (file)=>{ + let session = JSON.parse(await file.text()) + session = new Session(clone(session, true)) + session.created = Date.now() + await this.#db.write(session) + } + ev.preventDefault() + if (ev.dataTransfer.items) { + [...ev.dataTransfer.items].forEach(async (item, i) => { + if (item.kind === "file") { + const file = item.getAsFile(); + insert(file) + + } + }); + } else { + [...ev.dataTransfer.files].forEach(async (file, i) => { + insert(file) + }); + } + + } + + #initializeSessioEditor() { + this.#sessionEditor.db = this.#db + + this.#sessionEditor.addEventListener(DatabaseSessionList.TRIGGER_LOAD, this.binding(this.#onTriggerLoad)) + this.#sessionEditor.addEventListener(LayoutManager.NEW_SESSION, this.binding(this.#onNewSession)) + this.#sessionEditor.addEventListener(LayoutManager.DUPLICATE_SESSION, this.binding(this.#onDuplicateSession)) + this.#sessionEditor.addEventListener(LayoutManager.EXPORT_SESSION, this.binding(this.#onExportSession)) + this.#sessionEditor.addEventListener(LayoutManager.DELETE_SESSION, this.binding(this.#onTriggerDelete)) + + this.#sessionEditor.addEventListener(SessionEditor.ZERO, this.binding(this.#onZeroClick)) + } + + + #onZeroClick(e) { + this.#sessionManager.zeroAll(e.detail, false) + } + + #initializeKeyboard() { + + this.#keyboard.classList.add("keyboard-section") + this.#keyboard.addEventListener(Keyboard.KEYDOWN, (e)=>{ + if (this.#session.keyboardFocus) { + const validPath = this.#session.getValidSubpath(this.#session.keyboardFocus) + if (validPath.length >= 2) { + const ref = this.#session.getPathReference(validPath) + if (ref.length) ref.length = 1/e.detail.keydown.frequency + else if (ref.oscillator && ref.oscillator.length) ref.oscillator.length = 1/e.detail.keydown.frequency + } + } + + }) + this.#keyboard.addEventListener(Keyboard.KEYUP, (e)=>{ + }) + this.#keyboard.addEventListener(Keyboard.KEYPRESSURE, (e)=>{ + }) + this.#keyboard.addEventListener(Keyboard.KEYBEND, (e)=>{ + }) + } + + async #initializeDatabase() { + await this.#db.open() + } + + async #initalizeAudioEngine() { + await this.#sessionManager.inititialize() + } + + async #loadRecentOrDefault() { + let session = await this.#db.recent() + + if (session) return new Session(session) + return new Session(defaultSession()) + } + + + async #onSplashScreenDismiss(e) { + await this.#initalizeAudioEngine() + await this.#initializeDatabase() + const session = await this.#loadRecentOrDefault() + + this.#initializeKeyboard() + this.#initializeSessioEditor() + + this.session = session + + this.addToRenderQueue(this.binding(this.#removeSplashScreen)) + } + + #removeSplashScreen() { + this.#splashScreen.remove() + + this.shadowRoot.append(this.#sessionEditor) + this.shadowRoot.append(this.#keyboard) + + } + + async #onTriggerLoad(e) { + const rawSession = await this.#db.read(e.detail) + if (rawSession && (!this.#session || rawSession.id !== this.#session.id)) { + await this.#sessionManager.stopAll() + rawSession.mode = "storage" + this.session = new Session(rawSession) + this.#save() + } + } + + async #onTriggerDelete(e) { + if (!this.#session) return + await this.#sessionManager.stopAll() + const id = this.#session.id + this.session = null + await this.#db.delete(id) + } + + async #onNewSession(e) { + await this.#sessionManager.stopAll() + let session = new Session({mode:"storage"}) + await this.#db.write(session) + this.session = session + } + + async #onDuplicateSession(e) { + if (!this.#session) return + await this.#sessionManager.stopAll() + let session = new Session(clone(this.#session, true)) + session.created = Date.now() + await this.#db.write(session) + this.session = session + } + + async #onExportSession(e) { + if (!this.#session) return + downloadJSON(this.#session.name, this.#session) + } + + #updateKeyboard() { + if (!this.#session || this.#session.mode === "storage") { + this.#keyboard.remove() + } else { + this.shadowRoot.append(this.#keyboard) + } + } + + #onSessionChange(signal) { + if (signal.path[0].property === "tempo") { + this.#session.syncTempo() + } else if (signal.path[0].property === "mode") { + this.#updateKeyboard() + } else if (signal.path[0].property === "state") { + if (signal.path[0].origin instanceof Channel) { + if (signal.path[0].origin.state === Channel.DELETE) { + const channelIndex = this.#session.channels.indexOf(signal.path[0].origin) + this.#session.channels.splice(channelIndex, 1) + this.#session.validateAllPaths() + } + } else if (signal.path[0].origin instanceof Voice) { + if (signal.path[0].origin.state === Voice.TRIGGER_ATTACK) { + signal.path[0].origin.state = Voice.ATTACK + } else if (signal.path[0].origin.state === Voice.TRIGGER_RELEASE) { + signal.path[0].origin.state = Voice.RELEASE + } else if (signal.path[0].origin.state === Voice.DELETE) { + const voice = signal.path[0].origin + const channel = signal.path[1].origin + const voiceIndex = channel.voices.indexOf(voice) + channel.voices.splice(voiceIndex, 1) + this.#session.validateAllPaths() + + } + } + } else if (signal.property === "activeView" || signal.path[0].property === "path") { + + const view = this.#session.views[this.#session.activeView] + if (view && view.path.length>=2) { + const validPath = this.#session.getValidSubpath(view.path) + + const ref = this.#session.getPathReference(validPath) + if (ref.length || ref.oscillator && ref.oscillator.length) { + this.#session.keyboardFocus = validPath + } + } + } + this.#save() + } + + async #save() { + if (!this.#session) return + if (!this.#saveReady) { + this.#saveTriggered = true + return + } + this.#saveTriggered = false + this.#saveReady = false + try { + await this.#db.write(this.#session) + setTimeout(()=>{ + this.#saveReady = true + if (this.#saveTriggered) { + this.#save() + } + }, this.#saveDelay) + } catch(e) { + console.error(e) + } + } + + get session() { + return this.#session + } + + set session(value) { + resetState(value) + this.#session = value + this.#sessionManager.session = this.#session + this.#sessionEditor.session = this.#session + this.#keyboard.session = this.#session + this.#updateKeyboard() + } + + destroy() { + this.#db.close() + super.destroy() + } +} diff --git a/src/component/button-list.css b/src/component/button-list.css new file mode 100644 index 0000000..e95fd76 --- /dev/null +++ b/src/component/button-list.css @@ -0,0 +1,13 @@ +:host { + user-select: none; + display: flex; + white-space: nowrap; + box-sizing: border-box; +} + +.container { + display: flex; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} \ No newline at end of file diff --git a/src/component/button-list.js b/src/component/button-list.js new file mode 100644 index 0000000..418ee32 --- /dev/null +++ b/src/component/button-list.js @@ -0,0 +1,47 @@ + +import updateUIList from "../data/update-ui-list.js" +import Component from "./component.js" +import Button from "./button.js" + + +export default class ButtonList extends Component { + + static style = 'component/button-list.css' + #container = document.createElement('div') + #items + + constructor() { + super() + this.intitialized = false + this.#container.classList.add("container") + this.#init() + } + + async #init() { + await this.appendStyleLink(ButtonList.style) + this.intitialized = true + this.shadowRoot.append(this.#container) + this.addToRenderQueue(this.binding(this.#render)) + } + + set items(value) { + this.#items = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get items() { + return this.#items + } + + #render() { + if (this.#items) { + updateUIList(this.#container, Button, this.#items) + } + } + + destroy() { + updateUIList(this.#container, Button, []) + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/button.css b/src/component/button.css new file mode 100644 index 0000000..a9f0335 --- /dev/null +++ b/src/component/button.css @@ -0,0 +1,120 @@ +:host { + user-select: none; + display: flex; + min-width: 90px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; +} + +:host(.wrap) { + flex-basis: 100%; + margin-top:-6px; +} + +:host(.invisible) { + margin-top:-6px; + min-height: 0; + height: 0; +} + +button { + cursor: pointer; + display: flex; + width: 90px; + height: 72px; + border: none; + color:#909090; + background-color: #121212; + align-items: center; + justify-content: space-between; + flex-direction: column; + padding: 6px; + margin: 0; +} + +button.active { + color: rgb(63,63,63); + background-color:rgb(255,255,255); + +} + +button.insert { + color: rgb(0,0,0); + background-color: #446b85; + +} + +button.delete { + color: rgb(0,0,0); + background-color: #c9b02e; + +} + +button.solo { + color: rgb(0,0,0); + background-color: #9e1500; + +} + +button.path { + color:rgb(255,255,255); + background-color: #343435; + +} + +button.logo { + color: rgb(255,255,255); + background-color: #112233; + +} + +button.toggle { + color:#909090; + background: none; +} + +button.toggle .label { + color:rgb(255,255,255); +} + +button.inactive { + color:#909090; + background: none; + cursor: default; +} + + +.label { + display: flex; + font-weight: bold; + font-size: 12px; + flex-wrap: wrap; + overflow-wrap: anywhere; + white-space: normal; +} + +.header { + display: flex; + font-size: 9px; + min-height: 12px; + line-height: 12px; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-start; + overflow: hidden; +} + +.footer { + display: flex; + font-size: 9px; + min-height: 12px; + line-height: 12px; + max-width: 100%; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-end; + overflow: hidden; + text-align: right; +} \ No newline at end of file diff --git a/src/component/button.js b/src/component/button.js new file mode 100644 index 0000000..f0bf4f0 --- /dev/null +++ b/src/component/button.js @@ -0,0 +1,192 @@ +import Component from "./component.js" + +export default class Button extends Component { + + static style = 'component/button.css' + + static UP = 'up' + static DOWN = 'down' + + #label = "" + #header = "" + #footer = "" + #wrap = false + #invisible = false + #action + #id + #path + + #mode = "default" + + #buttonEl = document.createElement("button") + #headerEl = document.createElement("div") + #labelEl = document.createElement("div") + #footerEl = document.createElement("div") + + #isDown + + constructor() { + super() + this.intitialized = false + + this.#headerEl.classList.add("header") + this.#buttonEl.append(this.#headerEl) + + this.#labelEl.classList.add("label") + this.#buttonEl.append(this.#labelEl) + + this.#footerEl.classList.add("footer") + this.#buttonEl.append(this.#footerEl) + + this.#init() + } + + async #init() { + await this.appendStyleLink(Button.style) + this.shadowRoot.append(this.#buttonEl) + this.addToRenderQueue(this.binding(this.#render)) + this.#buttonEl.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#buttonEl.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.#buttonEl.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + Button.DOWN, + { + detail: this, + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#buttonEl.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + Button.UP, + { + detail: this, + bubbles: true, + composed: true + } + ) + ) + } + + set wrap(value) { + this.#wrap = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get wrap() { + return this.#wrap + } + + set invisible(value) { + this.#invisible = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get invisible() { + return this.#invisible + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get label() { + return this.#label + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get header() { + return this.#header + } + + set footer(value) { + this.#footer = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get footer() { + return this.#footer + } + + set mode(value) { + this.#mode = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get mode() { + return this.#mode + } + + set action(value) { + this.#action = value + } + + get action() { + return this.#action + } + + set id(value) { + this.#id = value + } + + get id() { + return this.#id + } + + set path(value) { + this.#path = value + } + + get path() { + return this.#path + } + + #render() { + if (this.#wrap) this.shadowRoot.host.classList.add("wrap") + else this.shadowRoot.host.classList.remove("wrap") + if (this.#invisible) this.shadowRoot.host.classList.add("invisible") + else this.shadowRoot.host.classList.remove("invisible") + this.#labelEl.textContent = this.#label + this.#headerEl.textContent = this.#header + this.#footerEl.textContent = this.#footer + if (this.#mode === "toggle") this.#buttonEl.classList.add("toggle") + else this.#buttonEl.classList.remove("toggle") + if (this.#mode === "active") this.#buttonEl.classList.add("active") + else this.#buttonEl.classList.remove("active") + if (this.#mode === "insert") this.#buttonEl.classList.add("insert") + else this.#buttonEl.classList.remove("insert") + if (this.#mode === "delete") this.#buttonEl.classList.add("delete") + else this.#buttonEl.classList.remove("delete") + if (this.#mode === "path") this.#buttonEl.classList.add("path") + else this.#buttonEl.classList.remove("path") + if (this.#mode === "logo") this.#buttonEl.classList.add("logo") + else this.#buttonEl.classList.remove("logo") + if (this.#mode === "solo") this.#buttonEl.classList.add("solo") + else this.#buttonEl.classList.remove("solo") + if (this.#mode === "inactive") this.#buttonEl.classList.add("inactive") + else this.#buttonEl.classList.remove("inactive") + } + + destroy() { + super.destroy() + } +} \ No newline at end of file diff --git a/src/component/channel-editor.css b/src/component/channel-editor.css new file mode 100644 index 0000000..f75fe62 --- /dev/null +++ b/src/component/channel-editor.css @@ -0,0 +1,14 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} \ No newline at end of file diff --git a/src/component/channel-editor.js b/src/component/channel-editor.js new file mode 100644 index 0000000..c78d49d --- /dev/null +++ b/src/component/channel-editor.js @@ -0,0 +1,152 @@ +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Dynamics from "../model/dynamics.js" +import Component from "./component.js" +import MetricsDisplay from "./metrics-display.js" +import Button from "./button.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import RotaryGroup from "./rotary-group.js" +import VoiceEditor from "./voice-editor.js" + +export default class ChannelEditor extends Component { + + static CHANGE = 'change' + static ZERO = 'zero' + static style = 'component/channel-editor.css' + + #voiceEditor = VoiceEditor.create() + + #zeroButton = Button.create() + #gainRotary = RotaryGroup.create() + #metricsDisplay = MetricsDisplay.create() + #potentialRotary = RotaryGroup.create() + #thresholdRotary = RotaryGroup.create() + #scaleRotary = RotaryGroup.create() + + #channel + + constructor() { + super() + this.intitialized = false + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + this.shadowRoot.append(this.#metricsDisplay) + + + this.#gainRotary.drivers = [ + new GainDriver() + ] + this.shadowRoot.append(this.#gainRotary) + + this.#potentialRotary.drivers = [ + new GainDriver({name:"Potential"}) + ] + this.shadowRoot.append(this.#potentialRotary) + + + this.#thresholdRotary.drivers = [ + new GainDriver({name: "Squeeze Threshold"}) + ] + this.shadowRoot.append(this.#thresholdRotary) + + + this.#scaleRotary.drivers = [ + new GainDriver({name: "Squeeze Scale", max: 4}) + ] + this.shadowRoot.append(this.#scaleRotary) + + + + + + watch(this, "channel", this.binding(this.#onChannelChange)) + this.#init() + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + ChannelEditor.ZERO, + { + composed: true, + detail: this.#channel.id + } + ) + ) + } + + async #init() { + await this.appendStyleLink(ChannelEditor.style) + this.#gainRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGainChange)) + this.#potentialRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onPotentialChange)) + this.#thresholdRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onThresholdChange)) + this.#scaleRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onScaleChange)) + + this.intitialized = true + } + + #onThresholdChange(e) { + this.#channel.dynamics.threshold = this.#thresholdRotary.value + } + + #onPotentialChange(e) { + this.#channel.dynamics.potential = this.#potentialRotary.value + } + + #onScaleChange(e) { + this.#channel.dynamics.scale = this.#scaleRotary.value + } + + + #onGainChange(e) { + this.#channel.gain = this.#gainRotary.value + } + + get channel() { + return this.#channel + } + + set channel(value) { + this.#channel = value + this.#metricsDisplay.audioMetrics = this.#channel.audioMetrics + this.#update() + } + + set settings(value) { + this.#voiceEditor.settings = value + } + + + #onChannelChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + || signal.path.length == 1 + ) this.#update() + + } + + #update() { + if (this.#channel) { + const voice = this.#channel.voices.find(voice => voice.id === this.#channel.activeVoice) + this.#voiceEditor.voice = voice + this.#potentialRotary.value = this.#channel.dynamics.potential + this.#thresholdRotary.value = this.#channel.dynamics.threshold + this.#scaleRotary.value = this.#channel.dynamics.scale + } + + this.#gainRotary.value = this.#channel.gain + + } + + destroy() { + unwatch(this, "channel", this.binding(this.#onChannelChange)) + super.destroy() + + } + +} \ No newline at end of file diff --git a/src/component/component.js b/src/component/component.js new file mode 100644 index 0000000..aff2bb1 --- /dev/null +++ b/src/component/component.js @@ -0,0 +1,117 @@ +import camelToKebab from "../utils/camel-to-kebab.js" + +export default class Component extends HTMLElement { + static prefix = "awsm" + static register = new Set() + + static get componentName() { + return [this.prefix, camelToKebab(this.name)].join('-') + } + + static create(opts) { + const name = this.componentName + if (!this.register.has(name)) { + customElements.define(name, this) + this.register.add(name) + } + const el = document.createElement(name) + if (opts) el.fromObject(opts) + return el + } + + #bindings = new Map() + #renderQueue = new Set() + #animationFrame + #initialized = true + #renderTriggered = false + #resizeObserver + + constructor({resizeObserver = true} = {}) { + super() + if (resizeObserver) { + this.#resizeObserver = new ResizeObserver(this.binding(this.#onResize)) + } + this.attachShadow({ mode: 'open' }) + } + + observe(el) { + this.#resizeObserver.observe(el) + } + + set intitialized(value) { + this.#initialized = value + if (this.#initialized && this.#renderTriggered) this.#triggerRender() + } + + get intitialized() { + return this.#initialized + } + + #onResize(entries) { + for (let entry of entries) { + + if (entry.contentBoxSize?.length > 0) { + this.resize({width: entry.contentBoxSize[0].inlineSize, height: entry.contentBoxSize[0].blockSize}) + break + } + } + } + + resize({width = 0, height = 0}) { + } + + async appendStyleLink(url) { + const styleEl = await new Promise((resolve, reject) => { + const styleEl = document.createElement('link'); + styleEl.type = 'text/css' + styleEl.rel = 'stylesheet' + styleEl.onload = () => resolve(styleEl) + styleEl.onerror = () => reject() + styleEl.href = url + this.shadowRoot.append(styleEl) + }) + return styleEl + } + + binding(fn) { + if (!this.#bindings) return + if (!this.#bindings.has(fn)) { + this.#bindings.set(fn, fn.bind(this)) + } + return this.#bindings.get(fn) + } + + /* Render on animation frame */ + addToRenderQueue(fn) { + if (!this.#renderQueue) return + this.#renderQueue.add(fn) + this.#triggerRender() + } + + /* Force immediate render. */ + render() { + if (this.#animationFrame) cancelAnimationFrame(this.#animationFrame) + this.#render() + } + + destroy() { + this.#bindings = null + this.#renderQueue = null + cancelAnimationFrame(this.#animationFrame) + this.remove() + } + + #triggerRender() { + this.#renderTriggered = false + if (this.#animationFrame) return + if (this.#initialized) this.#animationFrame = requestAnimationFrame(this.binding(this.#render)) + else this.#renderTriggered = true + } + + #render() { + this.#animationFrame = null + for (const fn of this.#renderQueue) fn() + this.#renderQueue = new Set() + } + +} \ No newline at end of file diff --git a/src/component/database-session-item.css b/src/component/database-session-item.css new file mode 100644 index 0000000..fbe3396 --- /dev/null +++ b/src/component/database-session-item.css @@ -0,0 +1,75 @@ +:host { + user-select: none; + display: flex; + width: 186px; + + height: 150px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + gap: 6px; + justify-content: space-between; + background-color: #121212; + color: #909090; + cursor: pointer; +} +:host(.active){ + background-color: #FFFFFF; + color: #000000; +} +canvas { + width: 186px; + height: 72px; + image-rendering: crisp-edges; +} +.container { + width: 186px; + padding: 6px; + height: 72px; + display: flex; + gap: 2px; + box-sizing: border-box; + flex-direction: column; +} +.name { + display: flex; + font-family: sans-serif; + font-weight: bold; + font-size: 12px; + flex-wrap: wrap; + align-content: center; + word-wrap: break-word; + white-space: normal; + +} + +.id { + display: flex; + font-family: sans-serif; + font-size: 9px; + word-wrap: unset; + text-overflow: ellipsis; + white-space: normal; + white-space: nowrap; + +} +.date { + display: flex; + font-family: sans-serif; + font-size: 9px; + flex-wrap: wrap; + word-wrap: break-word; + white-space: normal; + flex: 1; +} + +.channels { + display: flex; + font-family: sans-serif; + font-size: 9px; + flex-wrap: wrap; + word-wrap: break-word; + white-space: normal; + +} \ No newline at end of file diff --git a/src/component/database-session-item.js b/src/component/database-session-item.js new file mode 100644 index 0000000..348e2aa --- /dev/null +++ b/src/component/database-session-item.js @@ -0,0 +1,244 @@ + +import Component from "./component.js" +export default class DatabaseSessionItem extends Component { + + static style = 'component/database-session-item.css' + static UP = 'up' + static DOWN = 'down' + #tree + #name = "" + #id = "" + #changed = "" + #active = false + #isDown + #canvas = document.createElement("canvas") + #ctx + #container = document.createElement("div") + #nameElement = document.createElement("div") + #idElement = document.createElement("div") + #dateElement = document.createElement("div") + #channelsElement = document.createElement("div") + #voicesElement = document.createElement("div") + + constructor() { + super() + this.intitialized = false + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 180) + this.#canvas.setAttribute("height", 72) + + + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + + this.#container.classList.add("container") + this.shadowRoot.append(this.#container) + + this.#nameElement.classList.add("name") + this.#container.append(this.#nameElement) + + this.#idElement.classList.add("id") + this.#container.append(this.#idElement) + + this.#dateElement.classList.add("date") + this.#container.append(this.#dateElement) + + this.#channelsElement.classList.add("channels") + this.#container.append(this.#channelsElement) + + //this.#voicesElement.classList.add("channels") + //this.#container.append(this.#voicesElement) + + this.#init() + } + async #init() { + await this.appendStyleLink(DatabaseSessionItem.style) + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + DatabaseSessionItem.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + DatabaseSessionItem.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + set active(value) { + this.#active = value + this.addToRenderQueue(this.binding(this.#render)) + this.addToRenderQueue(this.binding(this.#renderTree)) + } + + get active() { + return this.#active + } + + set id(value) { + this.#id = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get id() { + return this.#id + } + + + set name(value) { + this.#name = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get name() { + return this.#name + } + + + set changed(value) { + this.#changed = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get changed() { + return this.#changed + } + + set tree(value) { + if (JSON.stringify(this.#tree) === JSON.stringify(value)) return + this.#tree = value + this.addToRenderQueue(this.binding(this.#renderTree)) + } + + get tree() { + return this.#tree + } + + #render() { + if (this.#active) this.classList.add("active") + else this.classList.remove("active") + this.#nameElement.textContent = this.#name + this.#idElement.textContent = this.#id + this.#dateElement.textContent = new Date(this.#changed).toISOString().replace('T', ' ').slice(0, -5) + + let voices = 0 + this.#tree.branches.forEach(channel => {voices += channel.branches.length}) + this.#channelsElement.textContent = `${this.#tree.branches.length} Channels, ${voices} Voices` + //this.#voicesElement.textContent = `${voices} Voices` + } + + #lineWidth = 4 + #branchDepth = 0 + #branchSpan = 0 + #padding = 6 + + + + #renderRecursive(x, y, branch, lineWidth=2) { + let sx = x-(branch.span * this.#branchSpan)/2 + this.#ctx.save() + const col = (this.#active)?"#000000":"#909090" + this.#ctx.strokeStyle = col + this.#ctx.lineWidth = lineWidth + this.#ctx.lineCap = "square" + for (let i = 0; i { + session.active = (this.#session && session.id === this.#session.id) + }) + updateUIList(this.#container, DatabaseSessionItem, sessions) + } + + destroy() { + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/display.css b/src/component/display.css new file mode 100644 index 0000000..ce43f98 --- /dev/null +++ b/src/component/display.css @@ -0,0 +1,87 @@ +:host { + user-select: none; + display: flex; + min-width: 90px; + min-height: 72px; + width: 90px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + padding: 6px; +} + +.container { + display:flex; + flex-direction: column; + flex: 1; + justify-content: space-between; +} + +.header, .footer{ + font-family: sans-serif; + color:rgb(128,128,128); + font-size: 9px; + height: 12px; + line-height: 12px; + align-self: flex-start; +} + +:host(.clickable) { + cursor: pointer; +} + +.footer { + display: flex; + font-size: 9px; + min-height: 12px; + line-height: 12px; + max-width: 100%; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-end; + overflow: hidden; + text-align: right; +} + +.mode { + display: flex; + flex-direction: row; + font-size: 12px; + margin-top: -2px; + height: 12px; + color:rgb(127,127,127); + gap: 3px; +} + +.value-container { + display:flex; + flex-direction: row; + align-items: baseline; + gap: 3px; + height: 28px; + max-width: 78px; + justify-content: center; +} + +.value { + display:flex; + font-family: sans-serif; + font-size: 24px; + color: rgba(255, 255, 255, 1); +} + +.unit { + display:flex; + font-family: sans-serif; + font-size: 11px; + color:rgba(255, 255, 255, 1); + vertical-align: baseline; +} + +.precision { + display:flex; + font-family: sans-serif; + font-size: 11px; + color:rgba(255, 255, 255, 1); + vertical-align: baseline; +} \ No newline at end of file diff --git a/src/component/display.js b/src/component/display.js new file mode 100644 index 0000000..6b7777a --- /dev/null +++ b/src/component/display.js @@ -0,0 +1,180 @@ +import Component from "./component.js" + +export default class Display extends Component { + + static UP = 'up' + static DOWN = 'down' + static CHANGE = 'change' + static style = 'component/display.css' + + #precisionEl = document.createElement('div') + #valueEl = document.createElement('div') + #headerEl = document.createElement('div') + #footerEl = document.createElement('div') + #modeEl = document.createElement('div') + #unitEl = document.createElement('div') + #containerEl = document.createElement('div') + #valueContainerEl = document.createElement('div') + + #precision = "" + #value = "0" + #label = "" + #unit = "Hz" + #footer = "" + + #modes = [] + #mode + + #isDown + #clickable = false + + constructor() { + super() + this.intitialized = false + this.#containerEl.classList.add("container") + this.#headerEl.classList.add("header") + this.#footerEl.classList.add("footer") + this.#modeEl.classList.add("mode") + this.#valueContainerEl.classList.add("value-container") + this.#precisionEl.classList.add("precision") + this.#valueEl.classList.add("value") + this.#unitEl.classList.add("unit") + this.#containerEl.appendChild(this.#headerEl) + this.#valueContainerEl.appendChild(this.#precisionEl) + this.#valueContainerEl.appendChild(this.#valueEl) + this.#valueContainerEl.appendChild(this.#unitEl) + this.#containerEl.appendChild(this.#valueContainerEl) + this.#containerEl.appendChild(this.#footerEl) + this.shadowRoot.append(this.#containerEl) + + this.#containerEl.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#containerEl.addEventListener("pointerup", this.binding(this.#onPointerUp)) + + this.#init() + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.#containerEl.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + Display.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#containerEl.releasePointerCapture(e.pointerId) + this.#isDown = null + this.dispatchEvent( + new CustomEvent( + Display.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + async #init() { + await this.appendStyleLink(Display.style) + this.intitialized = true + this.addToRenderQueue(this.binding(this.#render)) + } + + + set value(value) { + this.#value = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get value() { + return this.#value + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get label() { + return this.#label + } + + set unit(value) { + this.#unit = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get unit() { + return this.#unit + } + + set precision(value) { + this.#precision = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get precision() { + return this.#precision + } + + set footer(value) { + this.#footer = value + } + + get footer() { + return this.#footer + } + + set modes(value) { + this.#modes = value + } + + get modes() { + return this.#modes + } + + set mode(value) { + this.#mode = value + } + + get mode() { + return this.#mode + } + + set clickable(value) { + this.#clickable = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get clickable() { + return this.#clickable + } + + + #render() { + this.#headerEl.textContent = this.#label + this.#precisionEl.textContent = this.#precision + this.#valueEl.textContent = this.#value + this.#unitEl.textContent = this.#unit + this.#footerEl.textContent = this.#footer + if (this.#clickable && !this.shadowRoot.host.classList.contains("clickable")) this.shadowRoot.host.classList.add("clickable") + else if (!this.#clickable && this.shadowRoot.host.classList.contains("clickable")) this.shadowRoot.host.classList.remove("clickable") + + } + + destroy() { + + this.#containerEl.remove() + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/fm-editor.css b/src/component/fm-editor.css new file mode 100644 index 0000000..5e66d4b --- /dev/null +++ b/src/component/fm-editor.css @@ -0,0 +1,22 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: column; + gap: 6px; +} + +.container { + flex-direction: column; + max-width: 100%; +} + +canvas { + display:flex; +} \ No newline at end of file diff --git a/src/component/fm-editor.js b/src/component/fm-editor.js new file mode 100644 index 0000000..630789d --- /dev/null +++ b/src/component/fm-editor.js @@ -0,0 +1,63 @@ +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Component from "./component.js" +import RangeDriver from "./rotary-driver/range-driver.js" +import RotaryGroup from "./rotary-group.js" + +export default class FMEditor extends Component { + + static CHANGE = 'change' + static style = 'component/fm-editor.css' + + + #fmRangeRotary = RotaryGroup.create() + #waveSplineOscillator + + + constructor() { + super() + this.intitialized = false + this.#fmRangeRotary.drivers = [ + new RangeDriver() + ] + this.shadowRoot.append(this.#fmRangeRotary) + + this.#fmRangeRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onFMRangeChange)) + + watch(this, "waveSplineOscillator", this.binding(this.#onWaveSplineOscillatorChange)) + this.#init() + } + + #onFMRangeChange(e) { + this.#waveSplineOscillator.fmRange = this.#fmRangeRotary.value + } + + async #init() { + await this.appendStyleLink(FMEditor.style) + this.intitialized = true + } + + get waveSplineOscillator() { + return this.#waveSplineOscillator + } + + set waveSplineOscillator(value) { + this.#waveSplineOscillator = value + this.#update() + } + + #onWaveSplineOscillatorChange(signal) { + if (signal.path[0].property === "phase" || signal.path.length > 1) return + this.#update() + } + + #update() { + this.#fmRangeRotary.value = this.#waveSplineOscillator.fmRange + } + + destroy() { + unwatch(this, "waveSplineOscillator", this.binding(this.#onWaveSplineOscillatorChange)) + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/keyboard-group.css b/src/component/keyboard-group.css new file mode 100644 index 0000000..0340c9c --- /dev/null +++ b/src/component/keyboard-group.css @@ -0,0 +1,33 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; +} +.settings { + display: flex; + flex-direction: row; + flex-wrap: wrap; + margin: 6px; +} +.status { + height: 18px; + padding: 6px; + font-size: 9px; + line-height: 12px; + color: #909090; + font-family: sans-serif; +} +awsm-keyboard { + + width: 100%; + height: 72px; +} +.row { + display: flex; + flex-direction: row; +} \ No newline at end of file diff --git a/src/component/keyboard-group.js b/src/component/keyboard-group.js new file mode 100644 index 0000000..c708c23 --- /dev/null +++ b/src/component/keyboard-group.js @@ -0,0 +1,107 @@ +import watch from "../glue/watch.js" +import KeyboardSettings from "../model/keyboard-settings.js" +import Component from "./component.js" +import Keyboard from "./keyboard.js" + +export default class KeyboardGroup extends Component { + + static CHANGE = 'change' + static style = 'component/keyboard-group.css' + #keyboard = Keyboard.create() + #statusEl = document.createElement('div') + #session + + constructor() { + super() + this.intitialized = false + this.#statusEl.classList.add("status") + this.shadowRoot.append(this.#statusEl) + this.shadowRoot.append(this.#keyboard) + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(KeyboardGroup.style) + this.intitialized = true + this.#update() + } + + #onSessionChange(signal) { + if ( + signal.property === "activeView" + || signal.path[0].property === "path" + || signal.path[0].property === "length" + || signal.path[0].origin instanceof KeyboardSettings + || signal.path[0].property === "keyboardFocus" + ) this.#update() + } + + set session(value) { + this.#session = value + this.#update() + } + + get session() { + return this.#session + } + + + #getOscillatorName(oscillator) { + switch (oscillator) { + case "am": + return "AM" + case "fm": + return "FM" + case "transpose": + return "Pitch" + case "em": + return "Exponent" + case "sx": + return "Scale" + case "gain": + default: + return "Gain" + } + } + + #update() { + if (!this.#session) return + this.#keyboard.start = this.#session.keyboardSettings.start + this.#keyboard.keys = this.#session.keyboardSettings.keys + this.#keyboard.subdivisions = this.#session.keyboardSettings.subdivisions + + const validPath = this.#session.getValidSubpath(this.#session.keyboardFocus) + + const status = [] + if ( validPath.length>=2) { + const ref = this.#session.getPathReference(validPath) + if (ref.length) this.#keyboard.frequency = 1/ref.length + else if (ref.oscillator && ref.oscillator.length) this.#keyboard.frequency = 1/ref.oscillator.length + else this.#keyboard.frequency = 0 + const path = [] + status.push(this.#session.name) + let pref = this.#session + for(let i = 0; i 0) { + + const closest = new Note(findClosestNote(this.#frequency)) + if (Math.abs(closest.match - this.#frequency) < .001) { + highlight = closest.index + } + } + + for (let i=0; i{console.log(x.view.id, e.target.id);return x.view.id === e.target.id}) + console.log(node) + node.scrollIntoView() + } else if (e.target.action === "add-view") { + this.#session.views.push({}) + this.#session.activeView = this.#session.views.length - 1 + } else if (e.target.action === "delete-view") { + this.#session.views.splice(this.#session.activeView, 1) + this.#session.activeView = Math.min(this.#session.views.length - 1, this.#session.activeView) + } else if ( e.target.action === "show-storage") { + this.#session.mode = "storage" + } else if ( e.target.action === "show-view") { + if (this.#session) { + this.#session.mode = "view" + } + } else if ( e.target.action === "new-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.NEW_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } else if ( e.target.action === "delete-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.DELETE_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } else if ( e.target.action === "duplicate-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.DUPLICATE_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } else if ( e.target.action === "export-session") { + this.dispatchEvent( + new CustomEvent( + LayoutManager.EXPORT_SESSION, + { + bubbles: true, + composed: true + } + ) + ) + } + } + + #onContainerUp(e) { + let target = Array.from(this.#container.children).indexOf(e.target) + if (target<0) return + this.#session.activeView = target + + } + + set session(value) { + this.#session = value + this.#storageEditor.session = this.#session + } + + get session() { + return this.#session + } + + set db(value) { + this.#storageEditor.db = value + } + + get db() { + return this.#storageEditor.db + } + + #onSessionChange(signal) { + if (signal.path.length > 1) return + this.#update() + } + + #update() { + let list = [] + if (!this.#session) { + list.push(/*{ + header: "", + footer: "", + label: "AWSM", + mode: "logo", + invisible: false, + wrap: false + },*/{ + header: "AWSM", + footer: "",// "none", + label: "Database", + mode: "toggle", + action: "show-view", + invisible: false, + wrap: false + },{ + header: "Session", + footer: "", + label: "New", + mode: "insert", + action: "new-session", + invisible: false, + wrap: false + }) + } else if (this.#session.mode === "storage") { + list.push(/*{ + header: "", + footer: "", + label: "AWSM", + mode: "logo", + invisible: false, + wrap: false + },*/{ + header: "AWSM", + footer: "",// this.#session.name, + label: "Database", + mode: "logo", + action: "show-view", + invisible: false, + wrap: false + },{ + header: "Session", + footer: this.#session.name, + label: "Duplicate", + mode: "insert", + action: "duplicate-session", + invisible: false, + wrap: false + },{ + header: "Session", + footer: this.#session.name, + label: "Export", + mode: "insert", + action: "export-session", + invisible: false, + wrap: false + },{ + header: "Session", + footer: "", + label: "New", + mode: "insert", + action: "new-session", + invisible: false, + wrap: false + },{ + header: "Session", + footer: this.#session.name, + label: "Delete", + mode: "delete", + action: "delete-session", + invisible: false, + wrap: false + }) + } else if (this.#session.mode === "view") { + + + const views = this.#session.views.map((view, index) => {return { + session: this.#session, + view, + active: this.#session.activeView == index + }}) + updateUIList(this.#container, ViewEditor, views) + + list = this.#session.views.map( + (view, index) => { + return { + header: "View", + label: view.name, + footer: "", + mode: (this.#session.activeView == index) ? "active":"default", + action: "select-view", + id: index, + invisible: false, + wrap: false + } + } + ) + + list.unshift(/*{ + header: "", + footer: "", + label: "AWSM", + mode: "logo", + invisible: false, + wrap: false + },*/{ + header: "AWSM", + footer: "",//this.#session.name, + label: "Perform", + mode: "logo", + action: "show-storage", + invisible: false, + wrap: false + }) + list.push({ + header: "View", + label: "Add", + footer: "", + mode: "insert", + action: "add-view", + invisible: false, + wrap: false + }) + if (this.#session.activeView >= 0 && this.#session.activeView < this.#session.views.length) { + list.push({ + header: "View", + label: "Delete", + footer: this.#session.views[this.#session.activeView].name, + mode: "delete", + action: "delete-view", + invisible: false, + wrap: false + }) + } + } + + updateUIList(this.#navigationContent, Button, list) + this.addToRenderQueue(this.binding(this.#updateDom)) + + } + + #updateDom() { + + if (!this.#session || this.#session.mode === "storage") { + if (!this.#storageEditor.parentNode) this.shadowRoot.append(this.#storageEditor) + if (this.#container.parentNode) this.#container.remove() + } else { + if (!this.#container.parentNode) this.shadowRoot.append(this.#container) + if (this.#storageEditor.parentNode) this.#storageEditor.remove() + + } + } + + destroy() { + unwatch(this, "session", this.binding(this.#onSessionChange)) + super.destroy() + } +} \ No newline at end of file diff --git a/src/component/metrics-display.css b/src/component/metrics-display.css new file mode 100644 index 0000000..e7b4113 --- /dev/null +++ b/src/component/metrics-display.css @@ -0,0 +1,40 @@ +:host { + user-select: none; + display: flex; + width: 90px; + height: 72px; + white-space: nowrap; + box-sizing: border-box; + touch-action: none; + flex-direction: column; + flex:0; + padding: 6px; + cursor: pointer; +} + +canvas { + touch-action: none; + display:flex; + height: 36px; + width: 78px; +} + +.header, .footer{ + font-family: sans-serif; + color:rgb(128,128,128); + font-size: 9px; + height: 12px; + align-self: flex-start; +} + +.footer { + display: flex; + min-height: 12px; + line-height: 12px; + max-width: 100%; + flex-wrap: wrap; + overflow-wrap: anywhere; + align-self: flex-end; + overflow: hidden; + text-align: right; +} \ No newline at end of file diff --git a/src/component/metrics-display.js b/src/component/metrics-display.js new file mode 100644 index 0000000..3e87d11 --- /dev/null +++ b/src/component/metrics-display.js @@ -0,0 +1,152 @@ +import unwatch from "../glue/unwatch.js" +import Component from "./component.js" + +export default class MetricsDisplay extends Component { + + static CHANGE = 'change' + static style = 'component/metrics-display.css' + + #canvas = document.createElement('canvas') + #ctx + + #padding = 4 + #lineWidth = 2 + + #innerWidth + #innerHeight + #top + #left + + #audioMetrics + + #header = "" + #headerEl = document.createElement("div") + #footerEl = document.createElement("div") + #freeze = false + + constructor() { + super() + this.intitialized = false + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 60) + this.#canvas.setAttribute("height", 36) + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + + this.#footerEl.classList.add("footer") + this.shadowRoot.append(this.#footerEl) + + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + + this.#init() + } + + #onPointerUp(e) { + this.freeze = !this.freeze + } + + async #init() { + await this.appendStyleLink(MetricsDisplay.style) + this.#calculate() + this.#renderLabels() + this.#renderLoop() + this.intitialized = true + } + + resize(contentRect) { + super.resize(contentRect) + this.#calculate() + } + + set audioMetrics(value) { + this.#audioMetrics = value + } + + get audioMetrics() { + return this.#audioMetrics + } + + get header() { + return this.#header + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get header() { + return this.#header + } + + set freeze(value) { + this.#freeze = value + this.addToRenderQueue(this.binding(this.#renderLabels)) + } + + get freeze() { + return this.#freeze + } + + #calculate() { + this.#innerWidth = this.#canvas.width - this.#padding * 2 + this.#innerHeight = this.#canvas.height - this.#padding * 2 + this.#top = this.#padding + this.#left = this.#padding + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #renderLoop() { + requestAnimationFrame(()=>{ + this.#renderCanvas() + this.#renderLoop() + }) + } + + #renderCanvas() { + + if (this.#freeze) return + this.#headerEl.textContent = this.#header || "Oscilloscope" + this.#ctx.clearRect(0, 0, this.#canvas.width, this.#canvas.height) + if (!this.#audioMetrics) return + this.#audioMetrics.callback() + let frame = this.#audioMetrics.frame + let hFactor = this.#innerWidth/frame.length + let vFactor = this.#innerHeight/0xFF + this.#ctx.save() + this.#ctx.beginPath() + this.#ctx.lineJoin = "round" + this.#ctx.strokeStyle = "#FFFFFF" + this.#ctx.lineWidth = this.#lineWidth + for (let i = 0; i < frame.length; i++) { + const val = frame[i] + const x = this.#left + i * hFactor + const y = this.#top + (0xFF-val) * vFactor + if (x==0) { + this.#ctx.moveTo(x,y) + } else { + this.#ctx.lineTo(x,y) + } + } + this.#ctx.stroke() + this.#ctx.restore() + } + + #renderLabels() { + if (this.#freeze) { + this.#footerEl.textContent = "paused" + } else { + this.#footerEl.textContent = "" + } + } + + destroy() { + unwatch(this) + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/multi-pole-fader.css b/src/component/multi-pole-fader.css new file mode 100644 index 0000000..52df7e9 --- /dev/null +++ b/src/component/multi-pole-fader.css @@ -0,0 +1,17 @@ +:host { + user-select: none; + display: flex; + min-width: 90px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex:0; + padding: 6px; + cursor: pointer; +} +canvas { + display:flex; + width: 78px; + height: 60px; +} \ No newline at end of file diff --git a/src/component/multi-pole-fader.js b/src/component/multi-pole-fader.js new file mode 100644 index 0000000..06da6cf --- /dev/null +++ b/src/component/multi-pole-fader.js @@ -0,0 +1,292 @@ +import hslToRgb from "../color/hsl-to-rgb.js" +import rgbaToCss from "../color/rgba-to-css.js" +import calculateAngle from "../math/calculate-angle.js" +import { TAU } from "../math/contants.js" +import calculateLength from "../math/calculate-length.js" +import Point from "../model/point.js" +import Component from "./component.js" +import calculateCirclePoint from "../math/calculate-circle-point.js" +import translatePoint from "../math/translate-point.js" +import interpolatePoint from "../math/interpolate-point.js" +import Signal from "../glue/signal.js" +import calculatePoleValue from "../math/calculate-pole-value.js" + + +export default class MultiPoleFader extends Component { + + static CHANGE = 'change' + static style = 'component/multi-pole-fader.css' + + #canvas = document.createElement('canvas') + #ctx + #poles = 6 + #position = new Point({x:0, y:0}) + + #angleOffset = -Math.PI/2 + #padding = 16 + #radius + #diameter + #segmentAngle + #perimeterSegments + #perimeterSegmentAngle + #magnitude + + + #perimeterColor = hslToRgb({h: 0, s: 0, l: 1}) + #handleColor = hslToRgb({h: 0, s: 0, l: 1}) + #lineWidth = 2 + #handleRadius = 4 + + + #brightness = 1 + + #isDown + + constructor() { + super() + this.intitialized = false + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 78) + this.#canvas.setAttribute("height", 60) + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + this.#init() + } + + async #init() { + await this.appendStyleLink(MultiPoleFader.style) + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointermove", this.binding(this.#onPointerMove)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.addEventListener("lostpointercapture", this.binding(this.#onPointerLost)) + this.addEventListener("pointercancel", this.binding(this.#onPointerCancel)) + Signal.subscribe(this.#position, this.binding(this.#onPositionChange)) + this.#calculate() + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.#positionFromEvent(e) + } + + #onPointerCancel(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerLost(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerMove(e) { + if (this.#isDown !== e.pointerId) return + this.#positionFromEvent(e) + } + + #positionFromEvent(e) { + let rect = this.#canvas.getBoundingClientRect(); + let x = e.clientX - rect.left + let y = e.clientY - rect.top + + // proportional + let p = { + x: ((x - this.#canvas.width / 2) / this.radius), + y: ((y - this.#canvas.height / 2) / this.radius) + } + + const distance = calculateLength(p.x, p.y) + if (distance > 1) { + // limit to perimeter + const angle = calculateAngle(p) + this.#position.x = Math.cos(angle); + this.#position.y = Math.sin(angle); + } else { + this.#position.x = p.x + this.#position.y = p.y + } + this.dispatchEvent( + new CustomEvent( + MultiPoleFader.CHANGE, + { + composed: true + } + ) + ) + } + + get position() { + return this.#position + } + + #onPositionChange() { + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + set brightness(value) { + this.#brightness = Math.max(1, value) + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get brightness() { + return this.#brightness + } + + set angleOffset(value) { + this.#angleOffset = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get angleOffset() { + return this.#angleOffset + } + + set poles(value) { + if (this.#poles == value) return + this.#poles = value + this.#calculate() + } + + get poles() { + return this.#poles + } + + get radius() { + return this.#radius + } + + get diameter() { + return this.#diameter + } + + get segmentAngle() { + return this.#segmentAngle + } + + get perimeterSegments() { + return this.#perimeterSegments + } + + get perimeterSegmentAngle() { + return this.#perimeterSegmentAngle + } + + get magnitude() { + return this.#magnitude + } + + #calculate() { + this.#diameter = Math.min( + this.#canvas.width - this.#padding * 2, + this.#canvas.height - this.#padding * 2 + ) + this.#radius = this.#diameter / 2 + if (this.poles > 0) { + this.#segmentAngle = TAU / this.#poles + if (!(this.#poles % 2)) { + this.#perimeterSegments = this.#poles + this.#perimeterSegmentAngle = this.#segmentAngle + } else { + this.#perimeterSegments = this.#poles * 2 + this.#perimeterSegmentAngle = this.#segmentAngle / 2 + } + this.#magnitude = Math.max(1, this.#poles / 2) + } + + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + calculatePoleValue(pole) { + return calculatePoleValue(pole, this.#poles, this.#position) + } + + #renderCanvas() { + let w = this.#canvas.width + let h = this.#canvas.height + let cx = w/2 + let cy = h/2 + let c = {x: w/2, y: h/2} + + this.#ctx.clearRect(0, 0, this.#canvas.width, this.#canvas.height) + this.#ctx.save() + + // circle + this.#ctx.beginPath(); + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.strokeStyle = rgbaToCss(this.#perimeterColor) + this.#ctx.arc(c.x, c.y, this.radius, 0, 2 * Math.PI); + this.#ctx.stroke(); + + if (this.#poles > 0) { + // axis + for (let i = 0; i < this.poles; i++) { + const angle = this.angleOffset + i * this.segmentAngle + let s = translatePoint(calculateCirclePoint(this.radius, angle), c) + let e = translatePoint(calculateCirclePoint(this.radius, angle + Math.PI), c) + this.#ctx.save() + this.#ctx.beginPath(); + let col = i*128/this.poles + this.#ctx.lineWidth = this.#lineWidth / 2 + this.#ctx.strokeStyle = "#808080" + this.#ctx.moveTo (s.x, s.y); + this.#ctx.lineTo (e.x, e.y); + this.#ctx.stroke(); + this.#ctx.restore() + } + + // poles + for (let i = 0; i < this.poles; i++) { + const angle = this.angleOffset + i * this.segmentAngle + let s = translatePoint(calculateCirclePoint(this.radius, angle), c) + let e = translatePoint(calculateCirclePoint(this.radius, angle + Math.PI), c) + let q = this.calculatePoleValue(i) + let t = interpolatePoint(s, e, q) + this.#ctx.save() + this.#ctx.beginPath() + this.#ctx.fillStyle = "#909090" + this.#ctx.arc(t.x, t.y, this.#handleRadius / 2, 0, 2 * Math.PI) + this.#ctx.fill() + this.#ctx.restore() + + this.#ctx.save() + this.#ctx.fillStyle = "#909090" + let tp = translatePoint(calculateCirclePoint(this.radius + 10, angle + Math.PI), c) + this.#ctx.font = "9px sans-serif" + this.#ctx.textBaseline = "middle" + this.#ctx.textAlign = "center" + this.#ctx.fillText(i+1, tp.x, tp.y) + this.#ctx.restore() + + + } + + // handle + this.#ctx.save() + this.#ctx.beginPath(); + this.#ctx.fillStyle = rgbaToCss(this.#handleColor) + this.#ctx.arc(cx + this.#position.x * this.radius, cy + this.#position.y * this.radius, this.#handleRadius, 0, 2 * Math.PI); + this.#ctx.fill() + this.#ctx.restore() + } + } + + destroy() { + Signal.unsubscribe(this.#position, this.binding(this.#onPositionChange)) + this.#canvas.removeEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + this.#canvas.removeEventListener("pointerup", this.binding(this.#onPointerUp)) + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/oscillator-editor.css b/src/component/oscillator-editor.css new file mode 100644 index 0000000..c1cc690 --- /dev/null +++ b/src/component/oscillator-editor.css @@ -0,0 +1,35 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + gap: 3px; +} + +.navigation { + display:flex; + flex: 1; + flex-direction: row; +} + +.row { + display:flex; + flex: 1; + flex-direction: row; +} +.toolbar { + display: flex; + flex-direction: row; +} + +awsm-wave-spline-graph { + flex: 1; +} + +canvas { + display:flex; +} \ No newline at end of file diff --git a/src/component/oscillator-editor.js b/src/component/oscillator-editor.js new file mode 100644 index 0000000..b4bd50c --- /dev/null +++ b/src/component/oscillator-editor.js @@ -0,0 +1,149 @@ +import watch from "../glue/watch.js" +import beautifyTime from "../music/beautify-time.js" +import Component from "./component.js" +import FMEditor from "./fm-editor.js" +import Button from "./button.js" +import WaveSplineEditor from "./wave-spline-editor.js" + +export default class OscillatorEditor extends Component { + + static ZERO = 'zero' + static style = 'component/oscillator-editor.css' + #last + #parent + #reference + #settings + #zeroButton = Button.create() + #waveSplineContainer = document.createElement('div') + #waveSplineEditor = WaveSplineEditor.create() + #fmEditor = FMEditor.create() + + constructor() { + super() + this.intitialized = false + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + this.#waveSplineContainer.append(this.#waveSplineEditor) + this.shadowRoot.append(this.#waveSplineContainer) + + watch(this, "reference", this.binding(this.#onReferenceChange)) + watch(this, "settings", this.binding(this.#onSettingsChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(OscillatorEditor.style) + this.intitialized = true + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + OscillatorEditor.ZERO, + { + composed: true, + detail: this.#reference.id + } + ) + ) + } + + set last(value) { + this.#last = value + this.#update() + } + + get last() { + return this.#last + } + + set parent(value) { + this.#parent = value + this.#update() + } + + get parent() { + return this.#parent + } + + set reference(value) { + this.#reference = value + } + + get reference() { + return this.#reference + } + + set settings(value) { + this.#settings = value + } + + get settings() { + return this.#settings + } + + #onReferenceChange(signal) { + if (signal.path.length && signal.path[0].property === "phase") return + if (signal.path.length == 1 || signal.path[0].property == "viewZoom") this.#update() + } + + #onSettingsChange(signal) { + if (signal.path.length == 1) this.#update() + } + + #update() { + if (!this.#reference || !this.#parent) return + let last = this.#last // validPath.slice(-1)[0] + let parent = this.#parent // this.#session.getPathReference(validPath.slice(0,-1)) + const ref = this.#reference // this.#session.getPathReference(validPath) + + if (last === "fm") this.#fmEditor.waveSplineOscillator = parent + if (last === "fm") { + if (!this.#fmEditor.parentElement) { + // add fm control + this.#waveSplineContainer.insertBefore(this.#fmEditor, this.#waveSplineEditor) + } + } else { + if (this.#fmEditor.parentElement) { + this.#fmEditor.remove() + } + } + + if (last === "fm") { + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "transpose") { + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "am") { + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "em") { + this.#waveSplineEditor.zero = 0 + this.#waveSplineEditor.minYLabel = 0 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "sx") { + this.#waveSplineEditor.zero = 0 + this.#waveSplineEditor.minYLabel = 0 + this.#waveSplineEditor.maxYLabel = 1 + } else if (last === "gain") { + this.#waveSplineEditor.zero = 0 + this.#waveSplineEditor.minYLabel = 0 + this.#waveSplineEditor.maxYLabel = 1 + + } + const time = beautifyTime(ref.length * ref.wave.viewZoom) + this.#waveSplineEditor.maxXLabel = `${time.value} ${time.unit}` + this.#waveSplineEditor.waveSplineOscillator = ref + this.#waveSplineEditor.settings = this.#settings + } + +} \ No newline at end of file diff --git a/src/component/rotary-driver/bar-driver.js b/src/component/rotary-driver/bar-driver.js new file mode 100644 index 0000000..17dc576 --- /dev/null +++ b/src/component/rotary-driver/bar-driver.js @@ -0,0 +1,44 @@ +import RotaryDriver from "./rotary-driver.js" + +export default class BarDriver extends RotaryDriver { + tempo = 120 / 60 / 4 + constructor(opts) { + super() + this.name = "Bars" + this.id = "bar" + this.min = 1 + this.max = 24 + this.step = 1 + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return this.max + } + + get minLabel() { + return this.min + } + + toLocal(value) { + return value * this.tempo + } + + fromLocal(value) { + return value / this.tempo + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/beat-driver.js b/src/component/rotary-driver/beat-driver.js new file mode 100644 index 0000000..4e52b72 --- /dev/null +++ b/src/component/rotary-driver/beat-driver.js @@ -0,0 +1,38 @@ +import beautifyTime from "../../music/beautify-time.js" +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" +import TimeDriver from "./time-driver.js" + +export default class BeatDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Beat length" + this.id = "beat" + this.min = 0.25 + this.step = 0.01 + this.max = 2 + this.center = this.min + Object.assign(this, opts) + } + + toLocal(value) { + return 1/value/4 + } + + fromLocal(value) { + return 1/(value*4) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + const unitObject = beautifyTime(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded,.1), + unit: unitObject.unit, + valueString: unitObject.value + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/bpm-driver.js b/src/component/rotary-driver/bpm-driver.js new file mode 100644 index 0000000..0dc34df --- /dev/null +++ b/src/component/rotary-driver/bpm-driver.js @@ -0,0 +1,35 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class BPMDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "BPM" + this.id = "bpm" + this.min = 1 + this.step = 1 + this.max = 240 + this.center = this.min + Object.assign(this, opts) + } + + toLocal(value) { + return value * 60 * 4 // length of one beat to bpm + } + + fromLocal(value) { + return value / 60 / 4 // bpm to length of one beat + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "bpm", + valueString: beautifyValue(rounded).value + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/exponent-driver.js b/src/component/rotary-driver/exponent-driver.js new file mode 100644 index 0000000..c8d8321 --- /dev/null +++ b/src/component/rotary-driver/exponent-driver.js @@ -0,0 +1,28 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class ExponentDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Exponent" + this.id = "exponent" + this.min = .5 + this.step = .01 + this.max = 1000 + this.scale = .2 + this.center = 1 + Object.assign(this, opts) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: beautifyValue(rounded).value + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/fraction-driver.js b/src/component/rotary-driver/fraction-driver.js new file mode 100644 index 0000000..63de79c --- /dev/null +++ b/src/component/rotary-driver/fraction-driver.js @@ -0,0 +1,47 @@ +import { fromFraction } from "../../math/from-fraction.js" +import toFraction from "../../math/to-fraction.js" +import RotaryDriver from "./rotary-driver.js" + +export default class FractionDriver extends RotaryDriver{ + tempo = 120 / 60 / 4 // length of one beat + constructor(opts) { + super() + this.name = "Fraction" + this.id = "fraction" + this.min = 1 / 64 + this.max = 1 + this.step = this.min + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return toFraction(this.max) + } + + get minLabel() { + return toFraction(this.min) + } + + toLocal(value) { + return value * this.tempo + } + + fromLocal(value) { + return value / this.tempo + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + //const rounded = this.round(limited) + const fractionStr = toFraction(limited) + const fractionVal = fromFraction(fractionStr) + return { + value: fractionVal, + precision: this.precisionString(local, fractionVal), + unit: "", + valueString: fractionStr + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/frequency-driver.js b/src/component/rotary-driver/frequency-driver.js new file mode 100644 index 0000000..f222424 --- /dev/null +++ b/src/component/rotary-driver/frequency-driver.js @@ -0,0 +1,46 @@ +import beautifyFrequency from "../../music/beautify-frequency.js" +import beautifyTime from "../../music/beautify-time.js" +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class FrequencyDriver extends RotaryDriver{ + constructor(opts) { + super() + this.name = "Frequency" + this.id = "frequency" + this.min = 1 + this.max = 22000 + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + const beautified = beautifyValue(this.max) + return `${beautified.value}${beautified.unit}` + } + + get minLabel() { + return beautifyTime(this.min).value + } + + toLocal(value) { + return 1/value + } + + fromLocal(value) { + return 1/value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const unitObject = beautifyFrequency(limited) + return { + value: this.round(limited), + precision: this.precisionString(local, limited), + unit: unitObject.unit, + valueString: unitObject.value + + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/gain-driver.js b/src/component/rotary-driver/gain-driver.js new file mode 100644 index 0000000..c361b6a --- /dev/null +++ b/src/component/rotary-driver/gain-driver.js @@ -0,0 +1,37 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class GainDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Gain" + this.id = "gain" + this.min = 0 + this.max = 1 + this.step = this.min + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return beautifyValue(this.max).value + } + + get minLabel() { + return beautifyValue(this.min).value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + const unitObject = beautifyValue(limited) + return { + value: limited, + precision: this.precisionString(local, rounded,.1), + unit: unitObject.unit, + valueString: unitObject.value + + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/grid-driver.js b/src/component/rotary-driver/grid-driver.js new file mode 100644 index 0000000..6e86f70 --- /dev/null +++ b/src/component/rotary-driver/grid-driver.js @@ -0,0 +1,39 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class GridDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Grid" + this.id = "grid" + this.min = 1 + this.step = 1 + this.max = 25 + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + return "∞" + } + + toLocal(value) { + return value + } + + fromLocal(value) { + return value >= this.max ? Number.MAX_SAFE_INTEGER : value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: (rounded<=this.max-1)?this.precisionString(local, rounded):"", + unit: "", + valueString: (rounded>=this.max)?"∞":rounded + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/keys-driver.js b/src/component/rotary-driver/keys-driver.js new file mode 100644 index 0000000..27b6e09 --- /dev/null +++ b/src/component/rotary-driver/keys-driver.js @@ -0,0 +1,27 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class KeysDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Keys" + this.id = "keys" + this.min = 1 + this.step = 1 + this.max = 48 + this.center = this.min + Object.assign(this, opts) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/note-driver.js b/src/component/rotary-driver/note-driver.js new file mode 100644 index 0000000..0e7588c --- /dev/null +++ b/src/component/rotary-driver/note-driver.js @@ -0,0 +1,43 @@ +import { PIANO_KEYS, getNote, getNoteByIndex } from "../../music/notes.js" +import RotaryDriver from "./rotary-driver.js" + +export default class NoteDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Note" + this.id = "note" + this.min = 0 + this.max = PIANO_KEYS.length-1 + this.center = this.min + this.step = 1 + Object.assign(this, opts) + } + + get maxLabel() { + return `${PIANO_KEYS[this.max].name}${PIANO_KEYS[this.max].octave}` + } + + get minLabel() { + return `${PIANO_KEYS[this.min].name}${PIANO_KEYS[this.min].octave}` + } + + toLocal(value) { + return getNote(1/value).index + } + + fromLocal(value) { + return 1/getNoteByIndex(Math.round(value)).match + } + + render(value) { + const local = this.toLocal(value) + const note = getNote(1/value) + return { + value: local, + precision: note.precision === "=" ? "" : note.precision, + unit: "", + valueString: `${note.name.toUpperCase()}${note.octave}` + + } + } +} diff --git a/src/component/rotary-driver/quantize-driver.js b/src/component/rotary-driver/quantize-driver.js new file mode 100644 index 0000000..7b4f054 --- /dev/null +++ b/src/component/rotary-driver/quantize-driver.js @@ -0,0 +1,40 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class QuantizeDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Quantize" + this.id = "quantize" + this.min = 1 + this.step = 1 + this.scale = .5 + this.max = 1025 + this.center = 1025 + Object.assign(this, opts) + } + + get maxLabel() { + return "∞" + } + + toLocal(value) { + return value + } + + fromLocal(value) { + return value >= this.max ? Number.MAX_SAFE_INTEGER : value + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: (rounded<=this.max-1)?this.precisionString(local, rounded):"", + unit: "", + valueString: (rounded>=this.max)?"∞":rounded + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/range-driver.js b/src/component/rotary-driver/range-driver.js new file mode 100644 index 0000000..6cee638 --- /dev/null +++ b/src/component/rotary-driver/range-driver.js @@ -0,0 +1,35 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class RangeDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "FM Range" + this.id = "range" + this.min = 0 + this.step = 1 + this.max = 48 + this.center = 1 + Object.assign(this, opts) + } + + toLocal(value) { + return ((value - 1) * 12) //((value/2) * 12) // from multiplicator base to notes + } + + fromLocal(value) { + return (value / 12)+1 // (value / 12) * 2 // from notes to multiplicator base + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/rotary-driver.js b/src/component/rotary-driver/rotary-driver.js new file mode 100644 index 0000000..547bca2 --- /dev/null +++ b/src/component/rotary-driver/rotary-driver.js @@ -0,0 +1,60 @@ +export default class RotaryDriver { + min = 0 + max = 1 + center = 0 + step = 0 + name = "" + id = "default" + scale = 1 + + constructor(opts) { + Object.assign(this, opts) + } + + precisionString(value, reference, precision=0.001) { + if (value < this.min) { + return "<" + } else if (value > this.max) { + return ">" + } else if (Math.round(value * precision) == Math.round(reference * precision)){ + return "" + } else { + return "≈" + } + } + + limit(value) { + return Math.min(this.max, Math.max(this.min, value)) + } + + round(value) { + if (this.step == 0) return value + return Math.round(value * 1 / this.step) * this.step + } + + toLocal(value) { + return value + } + + fromLocal(value) { + return value + } + + get maxLabel() { + return this.max + } + + get minLabel() { + return this.min + } + + render(value) { + const local = this.toLocal(value) + return { + value: local, + precision: "", + unit: "", + valueString: local + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/subdivision-driver.js b/src/component/rotary-driver/subdivision-driver.js new file mode 100644 index 0000000..7d0bfb4 --- /dev/null +++ b/src/component/rotary-driver/subdivision-driver.js @@ -0,0 +1,26 @@ +import beautifyValue from "../../music/beautify-value.js" +import RotaryDriver from "./rotary-driver.js" + +export default class SubdivisionDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Subdivisions" + this.min = 1 + this.step = 1 + this.max = 60 + this.center = this.min + Object.assign(this, opts) + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + return { + value: rounded, + precision: this.precisionString(local, rounded), + unit: "", + valueString: rounded + } + } +} \ No newline at end of file diff --git a/src/component/rotary-driver/time-driver.js b/src/component/rotary-driver/time-driver.js new file mode 100644 index 0000000..e6081fd --- /dev/null +++ b/src/component/rotary-driver/time-driver.js @@ -0,0 +1,39 @@ +import beautifyTime from "../../music/beautify-time.js" +import RotaryDriver from "./rotary-driver.js" + +export default class TimeDriver extends RotaryDriver { + constructor(opts) { + super() + this.name = "Time" + this.id = "time" + this.min = 1/20000 + this.max = 60 + this.step = this.min + this.center = this.min + Object.assign(this, opts) + } + + get maxLabel() { + const beautified = beautifyTime(this.max) + return `${beautified.value}${beautified.unit}` + } + + get minLabel() { + const beautified = beautifyTime(this.min) + return `${beautified.value*1000}μs` + } + + render(value) { + const local = this.toLocal(value) + const limited = this.limit(local) + const rounded = this.round(limited) + const unitObject = beautifyTime(limited) + return { + value: limited, + precision: this.precisionString(local, rounded,.1), + unit: unitObject.unit, + valueString: unitObject.value + + } + } +} \ No newline at end of file diff --git a/src/component/rotary-group.css b/src/component/rotary-group.css new file mode 100644 index 0000000..1c4a611 --- /dev/null +++ b/src/component/rotary-group.css @@ -0,0 +1,10 @@ +:host { + user-select: none; + display: flex; + flex-wrap: wrap; + white-space: nowrap; + overflow: hidden; + gap: 6px; + box-sizing: border-box; + flex-direction: row; +} \ No newline at end of file diff --git a/src/component/rotary-group.js b/src/component/rotary-group.js new file mode 100644 index 0000000..37a0373 --- /dev/null +++ b/src/component/rotary-group.js @@ -0,0 +1,166 @@ +import Component from "./component.js" +import Display from "./display.js" +import RotaryDriver from "./rotary-driver/rotary-driver.js" +import Rotary from "./rotary.js" + + +export default class RotaryGroup extends Component { + + static CHANGE = 'change' + static DRIVER_CHANGE = 'driver-change' + static style = 'component/rotary-group.css' + + + #rotary = Rotary.create() + #display = Display.create() + #value + + + #drivers = [RotaryDriver] + #driver = RotaryDriver.id + + + constructor() { + super() + this.intitialized = false + this.shadowRoot.append(this.#rotary) + this.shadowRoot.append(this.#display) + + this.#rotary.addEventListener(Rotary.CHANGE, this.binding(this.#onRotaryChange)) + this.#display.addEventListener(Display.UP, this.binding(this.#onDisplayClick)) + + this.#init() + } + + async #init() { + await this.appendStyleLink(RotaryGroup.style) + this.intitialized = true + this.#updateValue() + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #onRotaryChange(e) { + if (this.#driver) { + this.#value = this.#driver.fromLocal(this.#rotary.value) + } + } + + #onDisplayClick(e) { + this.nextDriver() + } + + nextDriver() { + const index = (this.#drivers.indexOf(this.#driver) + 1) % this.#drivers.length + this.driver = this.#drivers[index].id + this.dispatchEvent( + new CustomEvent( + RotaryGroup.DRIVER_CHANGE, { + bubbles: true, + composed: true + } + ) + ) + } + + previousDriver() { + const index = (this.#drivers.indexOf(this.#driver) + this.#drivers.length - 1) % this.#drivers.length + this.driver = this.#drivers[index].id + this.dispatchEvent( + new CustomEvent( + RotaryGroup.DRIVER_CHANGE, { + bubbles: true, + composed: true + } + ) + ) + } + + set drivers(value) { + this.#drivers = value + if (this.driver) this.driver = this.#driver.id + else this.driver = this.#drivers[0].id + this.#updateDrivers() + } + + get drivers() { + return this.#drivers + } + + set driver(id) { + this.#driver = this.#drivers.find((driver)=>{return driver.id === id}) + this.#updateLabels() + this.#updateValue() + this.#updateDrivers() + } + + get driver() { + if (!this.#driver) return "" + return this.#driver.id + } + + set value(value) { + this.#value = value + this.#updateValue() + } + + get value() { + return this.#value + + } + + get rotary() { + return this.#rotary + } + + #updateDrivers() { + + this.#display.modes = this.#drivers.map(driver=>driver.name) + this.#display.mode = this.#driver.name + + } + + #updateLabels() { + if (this.#driver) { + this.#rotary.min = this.#driver.min + this.#rotary.center = this.#driver.center + this.#rotary.minLabel = this.#driver.minLabel + this.#rotary.max = this.#driver.max + this.#rotary.step = this.#driver.step + this.#rotary.maxLabel = this.#driver.maxLabel + this.#rotary.header = this.#driver.name + this.#rotary.scale = this.#driver.scale + + if (this.#drivers.length > 1) { + this.#display.clickable = true + this.#display.footer = `Mode: ${this.#drivers.indexOf(this.#driver)+1}/${this.#drivers.length}` + } else { + this.#display.clickable = false + this.#display.footer = "" + + } + } + } + + #updateValue() { + if (this.#driver) { + const valueSet = this.#driver.render(this.#value) + this.#display.precision = valueSet.precision + this.#display.unit = valueSet.unit + this.#display.value = valueSet.valueString + this.#rotary.value = valueSet.value + } + } + + #renderCanvas() { + + } + + destroy() { + this.#rotary.removeEventListener(Rotary.CHANGE, this.binding(this.#onRotaryChange)) + this.#display.removeEventListener(Display.UP, this.binding(this.#onDisplayClick)) + this.#rotary.destroy() + this.#display.destroy() + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/rotary.css b/src/component/rotary.css new file mode 100644 index 0000000..5f1faf7 --- /dev/null +++ b/src/component/rotary.css @@ -0,0 +1,39 @@ +:host { + user-select: none; + display: flex; + width: 90px; + height: 72px; + white-space: nowrap; + /*overflow: hidden;*/ + box-sizing: border-box; + touch-action: none; + flex-direction: column; + flex:0; + padding: 6px; + cursor: pointer; +} + +canvas { + touch-action: none; + display:flex; + height: 36px; + width: 78px; +} + +.header, .footer{ + font-family: sans-serif; + color:#909090; + font-size: 9px; + height: 12px; + line-height: 12px; +} + +.header { + align-self: flex-start; +} + +.footer { + display: flex; + justify-content: space-between; + flex-direction: row; +} diff --git a/src/component/rotary.js b/src/component/rotary.js new file mode 100644 index 0000000..0318532 --- /dev/null +++ b/src/component/rotary.js @@ -0,0 +1,359 @@ + +import hslToRgb from "../color/hsl-to-rgb.js" +import rgbaToCss from "../color/rgba-to-css.js" +import calculateAngleBetween from "../math/calculate-angle-between.js" +import calculateAngle from "../math/calculate-angle.js" +import calculateCirclePoint from "../math/calculate-circle-point.js" +import { TAU } from "../math/contants.js" +import translatePoint from "../math/translate-point.js" +import wrapAngle from "../math/wrap-angle.js" +import Component from "./component.js" + +export default class Rotary extends Component { + + static CHANGE = 'change' + static style = 'component/rotary.css' + + #canvas = document.createElement('canvas') + #ctx + + #angleOffset = -Math.PI/2 + #fromAngle = -.8 * Math.PI + #toAngle = .8 * Math.PI + #value = 0 + #min = -1 + #max = 1 + #center = 0 + //#paddingFactor = .2 + #padding = 5 + #labelSpacing = 14 + #step = 0 + #radius + #diameter + #width + #height + #innerRadius + #segmentAngle + #segmentHeight + #perimeterColor = hslToRgb({h: 0, s: 0, l: 1}) + #backgroundColor = hslToRgb({h: 0, s: 0, l: .5}) + #handleColor = hslToRgb({h: 0, s: 0, l: 1}) + #lineWidth = 2 + #handleRadius = 3 + #minLabel = "" + #maxLabel = "" + #header = "" + #footer = "" + #headerEl = document.createElement("div") + #footerEl = document.createElement("div") + #minEl = document.createElement("div") + #maxEl = document.createElement("div") + + #scale = 1 + + #isDown + + constructor() { + super() + this.intitialized = false + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 78) + this.#canvas.setAttribute("height", 36) + this.#ctx = this.#canvas.getContext("2d") + this.shadowRoot.append(this.#canvas) + + this.#footerEl.classList.add("footer") + this.#minEl.classList.add("min") + this.#footerEl.append(this.#minEl) + this.#maxEl.classList.add("max") + this.#footerEl.append(this.#maxEl) + this.shadowRoot.append(this.#footerEl) + + this.#init() + } + + async #init() { + await this.appendStyleLink(Rotary.style) + this.#calculate() + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointermove", this.binding(this.#onPointerMove)) + this.addEventListener("pointercancel", this.binding(this.#onPointerCancel)) + this.addEventListener("lostpointercapture", this.binding(this.#onPointerLost)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.intitialized = true + } + + + #onPointerDown(e) { + if (this.#isDown) return + if (e.button != 0) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + if (e.button != 0) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerCancel(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerLost(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + } + + #onPointerMove(e) { + if (this.#isDown !== e.pointerId) return + this.#positionFromEvent(e) + } + + #positionFromEvent(e) { + let rect = this.#canvas.getBoundingClientRect(); + let x = e.clientX - rect.left + let y = e.clientY - rect.top + + // proportional + let p = { + x: ((x - this.#canvas.width / 2) / this.radius), + y: ((y - this.#canvas.height / 2) / this.radius) + } + let w = this.#canvas.width + let h = this.#canvas.height + + const angle = calculateAngle(p) - this.#angleOffset + + + let start = wrapAngle(this.#fromAngle) + let end = wrapAngle(this.#toAngle) + let range = calculateAngleBetween(this.#fromAngle, this.#toAngle) + let value = calculateAngleBetween(start, angle) + let propValue = value / range + let inverseRange = TAU - range + //this.#value = Math.min(1,Math.max(0, propValue)) + let result + if (propValue < 1+inverseRange/TAU/2) { + result = Math.min(1, propValue) + } else if (propValue > 1+inverseRange/TAU/2) { + result = 0 + } else { + result = Math.min(1, Math.max(0, propValue)) + } + + if (this.#scale != 1) { + result = Math.pow(result, 1/this.#scale) + } + + this.#value = result + + this.addToRenderQueue(this.binding(this.#renderCanvas)) + this.dispatchEvent( + new CustomEvent( + Rotary.CHANGE, + { + composed: true + } + ) + ) + } + + get value() { + let result = this.#value * (this.#max-this.#min) + this.#min + if (this.step > 0) { + result = Math.round(result / this.step) * this.step + } + return result + } + + + + set value(value) { + this.#value = Math.max(0, Math.min(1,(value - this.#min) / (this.#max-this.#min))) + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + + get step() { + return this.#step + } + + set step(value) { + this.#step = value + } + + + get min() { + return this.#min + } + + set min(value) { + this.#min = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get minLabel() { + return this.#minLabel + } + + set minLabel(value) { + this.#minLabel = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get max() { + return this.#max + } + + set max(value) { + this.#max = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get maxLabel() { + return this.#maxLabel + } + + set maxLabel(value) { + this.#maxLabel = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get center() { + return this.#center + } + + set center(value) { + this.#center = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get scale() { + return this.#scale + } + + set scale(value) { + this.#scale = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + set angleOffset(value) { + this.#angleOffset = Math.max(1, value) + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get angleOffset() { + return this.#angleOffset + } + + get radius() { + return this.#radius + } + + get diameter() { + return this.#diameter + } + + get header() { + return this.#header + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + + + #calculate() { + this.#diameter = Math.min( + this.#canvas.width - this.#padding * 2, + this.#canvas.height - this.#padding * 2 + ) + this.#radius = this.#diameter / 2 + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #renderCanvas() { + + let w = this.#canvas.width + let h = this.#canvas.height + if (!w || !h) return console.log(w,h) + let c = {x: w/2, y: h/2} + + let val = Math.max(0, Math.min(1,(this.value - this.#min) / (this.#max-this.#min))) + + if (this.#scale != 1) { + val = Math.pow(val, this.#scale) + } + + let start = this.#fromAngle + this.#angleOffset + let end = this.#toAngle + this.#angleOffset + let overallRange = calculateAngleBetween(start, end) + let range = overallRange * val + + let valueAngle = start + range + + this.#ctx.clearRect(0, 0, this.#canvas.width, this.#canvas.height) + this.#ctx.save() + + // circle + this.#ctx.beginPath(); + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.strokeStyle = "#909090" // rgbaToCss(this.#backgroundColor) + this.#ctx.arc(c.x, c.y, this.radius, start, end); + this.#ctx.stroke(); + + // circle + this.#ctx.beginPath(); + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.strokeStyle = rgbaToCss(this.#perimeterColor) + + let valRange = Math.abs(this.#max - this.#min) + let propCenter = (this.#center-this.#min) / valRange + let centerAngle = start + (propCenter * overallRange) + let ccw = (centerAngle > valueAngle) + + this.#ctx.arc(c.x, c.y, this.radius, centerAngle, valueAngle, ccw); + this.#ctx.stroke(); + + + let s = translatePoint(calculateCirclePoint(this.radius, valueAngle), c) + // handle + this.#ctx.save() + this.#ctx.beginPath(); + this.#ctx.fillStyle = rgbaToCss(this.#handleColor) + this.#ctx.arc(s.x , s.y, this.#handleRadius, 0, 2 * Math.PI); + this.#ctx.fill(); + + this.#ctx.restore() + + this.#headerEl.textContent = this.#header + + const minLabel = this.minLabel || this.min + const maxLabel = this.maxLabel || this.max + this.#minEl.textContent = minLabel + this.#maxEl.textContent = maxLabel + + } + + destroy() { + + this.#canvas.removeEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + this.#canvas.removeEventListener("pointerup", this.binding(this.#onPointerUp)) + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/session-editor.css b/src/component/session-editor.css new file mode 100644 index 0000000..4fa98ce --- /dev/null +++ b/src/component/session-editor.css @@ -0,0 +1,18 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} +.container { + flex-direction: column; + max-width: 100%; +} \ No newline at end of file diff --git a/src/component/session-editor.js b/src/component/session-editor.js new file mode 100644 index 0000000..3e59820 --- /dev/null +++ b/src/component/session-editor.js @@ -0,0 +1,171 @@ + +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Dynamics from "../model/dynamics.js" +import Session from "../model/session.js" +import SessionMix from "./session-mix.js" +import Component from "./component.js" +import KeyboardSettingsEditor from "./keyboard-settings-editor.js" +import Button from "./button.js" +import BeatDriver from "./rotary-driver/beat-driver.js" +import BPMDriver from "./rotary-driver/bpm-driver.js" +import RotaryGroup from "./rotary-group.js" + +export default class SessionEditor extends Component { + static SOLO = 'solo' + static ZERO = 'zero' + static CHANGE = 'change' + static style = 'component/session-editor.css' + + + #stateToggle = Button.create() + #zeroButton = Button.create() + + #tempo = RotaryGroup.create() + #channelMix = SessionMix.create() + #keyboardSettingsEditor = KeyboardSettingsEditor.create() + #session + + #siblingsToggle = Button.create() + + + constructor() { + super() + this.intitialized = false + + + this.#stateToggle.header = "State" + this.#stateToggle.mode = "toggle" + this.shadowRoot.append(this.#stateToggle) + this.#stateToggle.addEventListener(Button.UP, this.binding(this.#onStateToggle)) + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + + + this.#tempo.drivers = [ + new BPMDriver(), + new BeatDriver({name:"Beat length"}) + ] + + this.#tempo.addEventListener(RotaryGroup.DRIVER_CHANGE, this.binding(this.#onTempoDriverChange)) + this.shadowRoot.append(this.#tempo) + + + this.shadowRoot.append(this.#channelMix) + + this.shadowRoot.append(this.#keyboardSettingsEditor) + + + + this.#siblingsToggle.header = "View Navigation" + this.#siblingsToggle.mode = "toggle" + this.#siblingsToggle.addEventListener(Button.UP, this.binding(this.#onSiblingsToggle)) + this.shadowRoot.append(this.#siblingsToggle) + + + this.#tempo.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onTempoChange)) + + + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + + #onTempoChange(e) { + this.#session.settings.tempo = this.#tempo.value + } + #onTempoDriverChange(e) { + this.#session.settings.tempoDriver = this.#tempo.driver + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + SessionEditor.ZERO, + { + composed: true, + detail: this.#session.id + } + ) + ) + } + + #onStateToggle(e) { + if ( + this.#session.state === Session.PLAYING + || this.#session.state === Session.PLAY + || this.#session.state === Session.TRIGGER_PLAY + ) { + this.#session.state = Session.TRIGGER_PAUSE + } else if ( + this.#session.state === Session.PAUSED + || this.#session.state === Session.TRIGGER_PAUSE + || this.#session.state === Session.PAUSE + ) { + this.#session.state = Session.TRIGGER_PLAY + } + } + + #onSiblingsToggle(e) { + if (this.#session.navigationMode === Session.COMPACT) { + this.#session.navigationMode = Session.MULTILINE + } else if (this.#session.navigationMode === Session.MULTILINE) { + this.#session.navigationMode = Session.SIBLINGS + } else { + this.#session.navigationMode = Session.COMPACT + } + } + + async #init() { + await this.appendStyleLink(SessionEditor.style) + this.intitialized = true + } + + set session(value) { + this.#session = value + this.#channelMix.session = this.#session + this.#keyboardSettingsEditor.session = this.#session + this.#update() + } + + get session() { + return this.#session + } + + + #onSessionChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + || signal.path[0].property === "state" + || signal.path[0].property === "tempo" + || signal.path[0].property === "tempoDriver" + || signal.path[0].property === "showSiblings" + ) this.#update() + } + + #update() { + if (this.#session) { + + + if (this.#session.settings.tempoDriver) this.#tempo.driver = this.#session.settings.tempoDriver + + + this.#stateToggle.label = this.#session.state + this.#siblingsToggle.label = this.#session.navigationMode + this.#tempo.value = this.#session.settings.tempo + } + + } + + destroy() { + unwatch(this, "settings", this.binding(this.#onSessionChange)) + super.destroy() + + } + +} \ No newline at end of file diff --git a/src/component/session-mix.css b/src/component/session-mix.css new file mode 100644 index 0000000..8b245f2 --- /dev/null +++ b/src/component/session-mix.css @@ -0,0 +1,19 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + overflow-y: auto; + box-sizing: border-box; + max-width: 100%; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} + +.container { + flex-direction: column; + max-width: 100%; +} \ No newline at end of file diff --git a/src/component/session-mix.js b/src/component/session-mix.js new file mode 100644 index 0000000..efde357 --- /dev/null +++ b/src/component/session-mix.js @@ -0,0 +1,148 @@ + +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Dynamics from "../model/dynamics.js" +import Button from "./button.js" +import Component from "./component.js" +import MetricsDisplay from "./metrics-display.js" +import MultiPoleFader from "./multi-pole-fader.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import RotaryGroup from "./rotary-group.js" + +export default class SessionMix extends Component { + + static CHANGE = 'change' + static style = 'component/session-mix.css' + + + #soloToggle = Button.create() + #metricsDisplay = MetricsDisplay.create() + #channelMix = MultiPoleFader.create() + #gainRotary = RotaryGroup.create() + #potentialRotary = RotaryGroup.create() + #thresholdRotary = RotaryGroup.create() + #scaleRotary = RotaryGroup.create() + #session + + + constructor() { + super() + this.intitialized = false + + this.#soloToggle.header = "Solo" + this.#soloToggle.mode = "toggle" + this.shadowRoot.append(this.#soloToggle) + this.#soloToggle.addEventListener(Button.UP, this.binding(this.#onSoloToggle)) + + this.shadowRoot.append(this.#metricsDisplay) + + this.#channelMix.addEventListener(MultiPoleFader.CHANGE, this.binding(this.#onMixChange)) + this.shadowRoot.append(this.#channelMix) + + this.#gainRotary.drivers = [ + new GainDriver({name:"Main Volume"}) + ] + this.shadowRoot.append(this.#gainRotary) + + /*this.#potentialRotary.drivers = [ + new GainDriver({name:"Potential"}) + ] + this.shadowRoot.append(this.#potentialRotary)*/ + + + this.#thresholdRotary.drivers = [ + new GainDriver({name: "Squeeze Threshold"}) + ] + this.shadowRoot.append(this.#thresholdRotary) + + + this.#scaleRotary.drivers = [ + new GainDriver({name: "Squeeze Scale", max: 4}) + ] + this.shadowRoot.append(this.#scaleRotary) + + + + watch(this, "session", this.binding(this.#onSessionChange)) + this.#init() + } + + #onSoloToggle(e) { + this.#session.voiceSolo("") + } + + #onGainChange(e) { + this.#session.main = this.#gainRotary.value + } + + #onPotentialChange(e) { + this.#session.dynamics.potential = this.#potentialRotary.value + } + #onThresholdChange(e) { + this.#session.dynamics.threshold = this.#thresholdRotary.value + } + #onScaleChange(e) { + this.#session.dynamics.scale = this.#scaleRotary.value + } + + #onMixChange(e) { + + this.#session.channelMix.x = this.#channelMix.position.x + this.#session.channelMix.y = this.#channelMix.position.y + + } + + + async #init() { + await this.appendStyleLink(SessionMix.style) + + this.#gainRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGainChange)) + this.#potentialRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onPotentialChange)) + this.#thresholdRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onThresholdChange)) + this.#scaleRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onScaleChange)) + this.intitialized = true + } + + get session() { + return this.#session + } + + set session(value) { + this.#session = value + this.#metricsDisplay.audioMetrics = this.#session.audioMetrics + this.#update() + } + + #onSessionChange(signal) { + if ( + signal.path[0].origin instanceof Dynamics + || signal.path.length == 1 + ) this.#update() + } + + #update() { + this.#gainRotary.value = this.#session.main + this.#channelMix.poles = this.#session.channels.length + this.#channelMix.position.x = this.#session.channelMix.x + this.#channelMix.position.y = this.#session.channelMix.y + this.#potentialRotary.value = this.#session.dynamics.potential + this.#scaleRotary.value = this.#session.dynamics.scale + this.#thresholdRotary.value = this.#session.dynamics.threshold + if (this.#session.solo === "") { + this.#soloToggle.label = "off" + this.#soloToggle.mode = "inactive" + } else { + this.#soloToggle.label = "on" + this.#soloToggle.mode = "solo" + } + + + } + + destroy() { + unwatch(this, "session", this.binding(this.#onSessionChange)) + super.destroy() + + } + +} \ No newline at end of file diff --git a/src/component/splash-screen-animation.css b/src/component/splash-screen-animation.css new file mode 100644 index 0000000..5ce6a9c --- /dev/null +++ b/src/component/splash-screen-animation.css @@ -0,0 +1,67 @@ +:host { + position: relative; + display: flex; + align-items: center; + flex-direction: column; + box-sizing: border-box; + justify-content: space-between; + width: 282px; + height: 228px; +} + +:host(.logo) { + background-color: #112233; +} + + +:host(.icon) { + background-color: #001422; +} + +.header { + display: flex; + font-size: 12px; + min-height: 12px; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-start; + overflow: hidden; + padding: 6px; + color: rgba(255,255,255,1); +} + +.label { + display: flex; + font-size: 48px; + font-weight: bold; + flex-wrap: wrap; + word-wrap: break-word; + white-space: normal; + color: rgba(255,255,255,1); +} + +.canvas { + width: 282px; + height: 228px; + position: absolute; +} + +:host(.icon) .label { + color: rgba(255,255,255,1); + /*backdrop-filter: blur(10px);*/ + font-size: 42px; +} + +.footer { + display: flex; + font-size: 12px; + min-height: 12px; + max-width: 100%; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-end; + overflow: hidden; + text-align: right; + padding: 6px; + color: rgba(255,255,255,1); +} \ No newline at end of file diff --git a/src/component/splash-screen-animation.js b/src/component/splash-screen-animation.js new file mode 100644 index 0000000..14a2eb1 --- /dev/null +++ b/src/component/splash-screen-animation.js @@ -0,0 +1,227 @@ + +import rgbaToCss from "../color/rgba-to-css.js" +import WaveSpline from "../model/wave-spline.js" +import solveWaveSpline from "../wave-spline/solve-wave-spline.js" +import Component from "./component.js" + +export default class SplashScreenAnimation extends Component { + + static style = 'component/splash-screen-animation.css' + static UP = 'up' + static DOWN = 'down' + + #header = "" + #footer = "" + #label = "" + + #mode = "logo" + + #ctx + + #canvasEl = document.createElement("canvas") + #headerEl = document.createElement("div") + #labelEl = document.createElement("div") + #footerEl = document.createElement("div") + + #isDown + + + constructor() { + super() + this.intitialized = false + + this.#canvasEl.classList.add("canvas") + this.#ctx = this.#canvasEl.getContext("2d") + this.shadowRoot.append(this.#canvasEl) + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.#labelEl.classList.add("label") + this.shadowRoot.append(this.#labelEl) + + + this.#footerEl.classList.add("footer") + this.shadowRoot.append(this.#footerEl) + + this.#dataset = this.#generate() + + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.#init() + } + + async #init() { + await this.appendStyleLink(SplashScreenAnimation.style) + this.intitialized = true + this.#render() + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenAnimation.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenAnimation.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get header() { + return this.#header + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get label() { + return this.#label + } + + set footer(value) { + this.#footer = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get footer() { + return this.#footer + } + + set mode(value) { + this.#mode = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get mode() { + return this.#mode + } + + #update() { + + this.classList.add("icon") + this.#headerEl.textContent = this.#header + this.#labelEl.textContent = this.#label + this.#footerEl.textContent = this.#footer + + } + + #layers = 7 + #minPoints = 4 + #maxPoints = 7 + + #generate() { + const layers = [] + for (let l = 0; l < this.#layers; l++) { + const points = this.#minPoints + Math.random() * (this.#maxPoints - this.#minPoints) + const layer = [] + for (let p = 0; p < points-1; p++) { + layer.push({x: 1/points*p, y: Math.random(), e: 2.341}) // 1 + Math.random() * 2}) + } + layers.push(new WaveSpline({points:layer})) + } + return layers + } + + #dataset = [] + + #maxV = 0.001 + #minA = 0.000007 + #maxA = 0.0007 + + #minPhase = .000007 + #maxPhase = .0007 + + #render() { + requestAnimationFrame(()=>{ + const d = this.#canvasEl.getBoundingClientRect() + if (this.#canvasEl.width != d.width) this.#canvasEl.width = d.width + if (this.#canvasEl.height != d.height) this.#canvasEl.height = d.height + const h = d.height *.5 + const oy = d.height * 0.25 + this.#ctx.clearRect(0,0, d.width, d.height) + this.#ctx.save() + this.#ctx.globalCompositeOperation = "screen"; + for (let i = 0; i.5?1:-1 + let p = null + this.#ctx.beginPath() + + const grd = this.#ctx.createLinearGradient(0, 0, 0, d.height); + grd.addColorStop(0.0, rgbaToCss({r:0,g:0,b:0,a:i/this.#dataset.length * .01}) ); + grd.addColorStop(0.5, rgbaToCss({r:255,g:255,b:255,a:i/this.#dataset.length * .05}) ); + grd.addColorStop(1, rgbaToCss({r:0,g:0,b:0,a:i/this.#dataset.length * .01}) ); + this.#ctx.fillStyle = grd + this.#ctx.lineWidth = 2 + if (this.#dataset[i].direction < 0) this.#ctx.moveTo(-2, -2) + else this.#ctx.moveTo(-2, d.height+2) + + for (let x = 0; x < d.width; x++) { + let y = solveWaveSpline(this.#dataset[i], (x/d.width + this.#dataset[i].phase + 1)%1) + + let c = {x: x, y: y*h + oy} + this.#ctx.lineTo(c.x, c.y) + + } + if (this.#dataset[i].direction < 0) this.#ctx.lineTo(d.width+2, -2) + else this.#ctx.lineTo(d.width+2, d.height+2) + + this.#ctx.closePath() + this.#ctx.fill() + + + if (!this.#dataset[i].vp) { + this.#dataset[i].vp = this.#minPhase + Math.random() * (this.#maxPhase - this.#minPhase) + if (Math.random()>0.5) this.#dataset[i].vp *=-1 + } + this.#dataset[i].phase = (this.#dataset[i].phase + this.#dataset[i].vp + 1) % 1 + for (let p = 0; p < this.#dataset[i].points.length; p++) { + if (!this.#dataset[i].points[p].vy) { + this.#dataset[i].points[p].vy = this.#minA + Math.random() * (this.#maxA -this.#minA) + if (Math.random()>0.5) this.#dataset[i].points[p].vy *=-1 + } + if ( this.#dataset[i].points[p].y + this.#dataset[i].points[p].vy > 1 || this.#dataset[i].points[p].y + this.#dataset[i].points[p].vy < 0) this.#dataset[i].points[p].vy *= -1 + this.#dataset[i].points[p].y = Math.max(0, Math.min(1, (this.#dataset[i].points[p].y + this.#dataset[i].points[p].vy))) + } + + } + + this.#ctx.restore() + + this.#render() + }) + + } + + destroy() { + super.destroy() + + } +} \ No newline at end of file diff --git a/src/component/splash-screen-item.css b/src/component/splash-screen-item.css new file mode 100644 index 0000000..830ca0d --- /dev/null +++ b/src/component/splash-screen-item.css @@ -0,0 +1,53 @@ +:host { + display: flex; + align-items: center; + flex-direction: column; + box-sizing: border-box; + justify-content: space-between; + padding: 6px; + width: 282px; + height: 228px; +} + +:host(.logo) { + background-color: #121212; + color: #909090; + cursor: pointer; +} + +:host(.icon) { + background-color: #061422; +} + +.header { + display: flex; + font-size: 12px; + text-wrap: pretty; + min-height: 12px; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-start; + overflow: hidden; +} + +.label { + display: flex; + font-size: 12px; + flex: 1; + font-weight: normal; + flex-wrap: wrap; + word-wrap: break-word; + white-space: pre-line; +} + +.footer { + display: flex; + font-size: 12px; + min-height: 12px; + max-width: 100%; + flex-wrap: wrap; + word-wrap: break-word; + align-self: flex-end; + overflow: hidden; + text-align: right; +} \ No newline at end of file diff --git a/src/component/splash-screen-item.js b/src/component/splash-screen-item.js new file mode 100644 index 0000000..b1e3b94 --- /dev/null +++ b/src/component/splash-screen-item.js @@ -0,0 +1,129 @@ + +import Component from "./component.js" + +export default class SplashScreenItem extends Component { + + static style = 'component/splash-screen-item.css' + static UP = 'up' + static DOWN = 'down' + + #label = "" + #header = "" + #footer = "" + + #mode = "default" + + #labelEl = document.createElement("div") + #headerEl = document.createElement("div") + #footerEl = document.createElement("div") + + #isDown + + + constructor() { + super() + this.intitialized = false + + + this.#labelEl.classList.add("label") + this.#labelEl.textContent = "AWSM" + this.shadowRoot.append(this.#labelEl) + + this.#footerEl.classList.add("footer") + this.#footerEl.textContent = "MKII" + this.shadowRoot.append(this.#footerEl) + + this.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.#init() + } + + async #init() { + await this.appendStyleLink(SplashScreenItem.style) + this.intitialized = true + } + + #onPointerDown(e) { + if (this.#isDown) return + this.#isDown = e.pointerId + this.setPointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenItem.DOWN, + { + bubbles: true, + composed: true + } + ) + ) + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.releasePointerCapture(e.pointerId) + this.dispatchEvent( + new CustomEvent( + SplashScreenItem.UP, + { + bubbles: true, + composed: true + } + ) + ) + } + + set label(value) { + this.#label = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get label() { + return this.#label + } + + set header(value) { + this.#header = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get header() { + return this.#header + } + + set footer(value) { + this.#footer = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get footer() { + return this.#footer + } + + set mode(value) { + this.#mode = value + this.addToRenderQueue(this.binding(this.#render)) + } + + get mode() { + return this.#mode + } + + #render() { + + if (this.#mode === "logo") this.classList.add("logo") + else this.classList.remove("logo") + if (this.#mode === "icon") this.classList.add("icon") + else this.classList.remove("icon") + + this.#labelEl.textContent = this.#label + this.#headerEl.textContent = this.#header + this.#footerEl.textContent = this.#footer + + } + + destroy() { + super.destroy() + + } +} \ No newline at end of file diff --git a/src/component/splash-screen.css b/src/component/splash-screen.css new file mode 100644 index 0000000..3a1d3f8 --- /dev/null +++ b/src/component/splash-screen.css @@ -0,0 +1,22 @@ +:host { + font-family: sans-serif; + color: #FFFFFF; + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + overflow: hidden; +} + +.container { + display: flex; + align-items: center; + flex-direction: row; + box-sizing: border-box; + justify-content: center; + flex-wrap: wrap; + gap: 6px; + min-height: 180px; +} + diff --git a/src/component/splash-screen.js b/src/component/splash-screen.js new file mode 100644 index 0000000..b9f5b27 --- /dev/null +++ b/src/component/splash-screen.js @@ -0,0 +1,58 @@ +import Component from "./component.js" +import SplashScreenAnimation from "./splash-screen-animation.js" +import SplashScreenItem from "./splash-screen-item.js" + +export default class SplashScreen extends Component { + + static DISMISS = "dismiss" + static style = 'component/splash-screen.css' + + #container = document.createElement("div") + #info = SplashScreenItem.create() + #logo = SplashScreenAnimation.create() + + constructor() { + super() + this.intitialized = false + + this.#container.classList.add("container") + this.shadowRoot.append(this.#container) + + this.#logo.header = "" + this.#logo.label = "AWSM" + this.#logo.footer = "" + this.#logo.mode = "icon" + this.#container.append(this.#logo) + + this.#info.label = "AwesomeWaveSplineMachine MKII\n\nTo continue, you must agree that your browser's database is used to persist your sessions. All your actions will be saved automatically.\n\nBe careful, this software is theoretically capable of destroying your precious speakers.\n\nUse on your own risk!" + this.#info.footer = "Click to agree and continue" + this.#info.mode = "logo" + this.#container.append(this.#info) + + + this.#info.addEventListener(SplashScreenItem.UP, this.binding(this.#onPointerUp)) + this.#init() + } + + async #init() { + await this.appendStyleLink(SplashScreen.style) + this.intitialized = true + } + + #onPointerUp(e) { + this.dispatchEvent( + new CustomEvent( + SplashScreen.DISMISS, + { + bubbles: true, + composed: true + } + ) + ) + } + + destroy() { + super.destroy() + + } +} \ No newline at end of file diff --git a/src/component/view-editor.css b/src/component/view-editor.css new file mode 100644 index 0000000..5e3c690 --- /dev/null +++ b/src/component/view-editor.css @@ -0,0 +1,59 @@ +:host { + user-select: none; + display: flex; + min-width: 102px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + max-width: 100%; + flex-direction: column; +} + +.status-indicator{ + height: 6px; + background-color: #121212; + margin-right: 12px; + +} + +.status-indicator.active { + background-color: #FFFFFF; + +} + +.container { + display: flex; + flex-direction: column; + overflow-x: hidden; + overflow-y: auto; + margin: 6px 0px 6px 0px; + padding-right: 6px; + gap: 6px; + flex: 1; +} + +/* Style the scrollbar background */ +::-webkit-scrollbar { + width: 6px; + height: 6px; + background: #000000; +} + +/* Style the scrollbar handle */ +::-webkit-scrollbar-thumb { + background: #303030; + border-radius: 0px; +} + +.mix { + display: flex; + flex-direction: column; +} + +.list { + display: flex; + flex-direction: column; + flex: 1; + max-width: 100%; +} \ No newline at end of file diff --git a/src/component/view-editor.js b/src/component/view-editor.js new file mode 100644 index 0000000..7fbfbee --- /dev/null +++ b/src/component/view-editor.js @@ -0,0 +1,148 @@ +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import ChannelEditor from "./channel-editor.js" +import Component from "./component.js" +import ViewNavigation from "./view-navigation.js" +import OscillatorEditor from "./oscillator-editor.js" +import SessionEditor from "./session-editor.js" +import VoiceEditor from "./voice-editor.js" + +export default class ViewEditor extends Component { + + static CHANGE = 'change' + static style = 'component/view-editor.css' + + #container = document.createElement('div') + #content = document.createElement('div') + #navigation = ViewNavigation.create() + #settingsEditor = SessionEditor.create() + #channelEditor = ChannelEditor.create() + #voiceEditor = VoiceEditor.create() + #oscillatorEditor = OscillatorEditor.create() + #statusIndicator = document.createElement("div") + + #session + #view + #active + + #activeContent + + constructor() { + super() + this.intitialized = false + this.shadowRoot.append(this.#statusIndicator) + this.shadowRoot.append(this.#container) + this.#container.classList.add('container') + + this.#container.append(this.#navigation) + this.#container.append(this.#content) + this.#statusIndicator.classList.add("status-indicator") + + this.#navigation.addEventListener(ViewNavigation.MODE, this.binding(this.#onNavigationModeChange)) + this.#voiceEditor.addEventListener(VoiceEditor.SOLO, this.binding(this.#onSoloToggle)) + + watch(this, "session", this.binding(this.#onSessionChange)) + watch(this, "view", this.binding(this.#onViewChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(ViewEditor.style) + this.intitialized = true + } + + set session(value) { + this.#session = value + } + + get session() { + return this.#session + } + + set view(value) { + this.#view = value + } + + get view() { + return this.#view + } + + set active(value) { + this.#active = value + this.addToRenderQueue(this.binding(this.#update)) + } + + get active() { + return this.#active + } + + #onSoloToggle(event) { + this.#session.voiceSolo(event.detail) + } + + #onNavigationModeChange(event) { + if (this.#navigation.mode === ViewNavigation.NAVIGATE) { + this.#container.append(this.#content) + } else { + this.#content.remove() + } + } + + #onSessionChange(signal) { + if (signal.path.length > 1) return + this.addToRenderQueue(this.binding(this.#update)) + } + + #onViewChange(signal) { + if (signal.path.length > 1) return + this.addToRenderQueue(this.binding(this.#update)) + } + + #update() { + if (!this.#session || !this.#view) return + this.#navigation.session = this.#session + this.#navigation.view = this.#view + + const validPath = this.#session.getValidSubpath(this.#view.path) + + let content + + if (this.#active) this.#statusIndicator.classList.add("active") + else this.#statusIndicator.classList.remove("active") + + if (validPath.length == 0) { + this.#settingsEditor.session = this.#session + content = this.#settingsEditor + } else if (validPath.length == 1) { + const id = validPath[0] + const channel = this.#session.findChannel(id) + this.#channelEditor.channel = channel + content = this.#channelEditor + } else if (validPath.length == 2) { + const channelId = validPath[0] + const channel = this.#session.findChannel(channelId) + const voiceId = validPath[1] + const voice = channel.findVoice(voiceId) + this.#voiceEditor.voice = voice + content = this.#voiceEditor + } else { + this.#oscillatorEditor.settings = this.#session.settings + this.#oscillatorEditor.last = validPath.slice(-1)[0] + this.#oscillatorEditor.parent = this.#session.getPathReference(validPath.slice(0,-1)) + this.#oscillatorEditor.reference = this.#session.getPathReference(validPath) + content = this.#oscillatorEditor + } + + if (content !== this.#activeContent) { + if (this.#activeContent) this.#activeContent.remove() + this.#activeContent = content + this.#content.append(this.#activeContent) + } + } + + destroy() { + unwatch(this, "session", this.binding(this.#onSessionChange)) + unwatch(this, "view", this.binding(this.#onViewChange)) + super.destroy() + } +} \ No newline at end of file diff --git a/src/component/view-navigation.css b/src/component/view-navigation.css new file mode 100644 index 0000000..96222b6 --- /dev/null +++ b/src/component/view-navigation.css @@ -0,0 +1,25 @@ +:host { + user-select: none; + display: flex; + white-space: nowrap; + box-sizing: border-box; +} + +.container { + display: flex; + flex-direction: column; + gap: 6px; +} + +.container.force-row { + + flex-direction: row; + flex-wrap: wrap; +} + +.item-row { + display: flex; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} \ No newline at end of file diff --git a/src/component/view-navigation.js b/src/component/view-navigation.js new file mode 100644 index 0000000..5246dea --- /dev/null +++ b/src/component/view-navigation.js @@ -0,0 +1,399 @@ +import clone from "../data/clone.js" +import updateUIList from "../data/update-ui-list.js" +import watch from "../glue/watch.js" +import Channel from "../model/channel.js" +import resetChannel from "../model/reset-channel.js" +import resetVoice from "../model/reset-voice.js" +import Session from "../model/session.js" +import Voice from "../model/voice.js" +import Component from "./component.js" +import Button from "./button.js" +import ButtonList from "./button-list.js" + +const INSERT_OSCILLATOR = "insert-oscillator" +const NAVIGATE = "navigate" + +export default class ViewNavigation extends Component { + + static CHANGE = 'change' + static MODE = 'mode' + static NAVIGATE ='navigate' + static INSERT_OSCILLATOR = "insert-oscillator" + static UP = 'up' + static style = 'component/view-navigation.css' + + #container = document.createElement('div') + #mode = NAVIGATE + #view + + #session + + constructor() { + super() + this.intitialized = false + this.#container.classList.add("container") + + this.#container.addEventListener(Button.UP, this.binding(this.#onButtonUp)) + watch(this, "session", this.binding(this.#onSessionChange)) + watch(this, "view", this.binding(this.#onViewChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(ViewNavigation.style) + this.intitialized = true + this.shadowRoot.append(this.#container) + this.addToRenderQueue(this.binding(this.#render)) + } + + #onButtonUp(e) { + e.stopPropagation() + const children = Array.from(this.#container.children) + + if (e.detail.action === "session") { + this.#view.path = [] + } + if (e.detail.action === "add-channel") { + this.#session.channels.push({}) + const channelId = this.#session.channels[this.#session.channels.length-1].id + this.#view.path = [channelId] + } + if (e.detail.action === "channel") { + this.#view.path = [e.detail.id] + } + if (e.detail.action === "add-voice") { + const channel = this.#session.findChannel(this.#view.path[0]) + channel.voices.push(clone(this.#session.defaults.voice, true)) + channel.voices[channel.voices.length-1].state = Voice.TRIGGER_ATTACK + const voiceId = channel.voices[channel.voices.length-1].id + this.#view.path = [this.#view.path[0], voiceId] + } + if (e.detail.action === "add-oscillator") { + const ref = this.#session.getPathReference(this.#view.path) + let empty = {} + if (e.detail.id === "fm") empty = clone(this.#session.defaults.fm, true) + else if (e.detail.id === "am") empty = clone(this.#session.defaults.am, true) + else if (e.detail.id === "em") empty = clone(this.#session.defaults.em, true) + else if (e.detail.id === "sx") empty = clone(this.#session.defaults.sx, true) + else if (e.detail.id === "gain") empty = clone(this.#session.defaults.gain, true) + else if (e.detail.id === "transpose") empty = clone(this.#session.defaults.transpose, true) + ref[e.detail.id] = empty + this.mode = NAVIGATE + this.#view.path.push(e.detail.id) + } + if (e.detail.action === "select-oscillator") { + this.mode = NAVIGATE + this.#view.path = e.detail.path + } + if (e.detail.action === "choose-oscillator") { + const ref = this.#session.getPathReference(this.#view.path) + this.mode = INSERT_OSCILLATOR + } + if (e.detail.action === "voice") { + this.mode = NAVIGATE + this.#view.path = [this.#view.path[0], e.detail.id] + } + if (e.detail.action === "toggle-collapse") { + this.mode = NAVIGATE + this.#view.navigationCollapsed = !this.#view.navigationCollapsed + } + if (e.detail.action === "delete-oscillator") { + + const ref = this.#session.getPathReference(this.#view.path.slice(0,-1)) + ref[e.detail.id] = null + this.#session.validateAllPaths() + } + if (e.detail.action === "duplicate-voice") { + const channel = this.#session.findChannel(this.#view.path[0]) + const voice = clone(channel.findVoice(this.#view.path[1]), true) + resetVoice(voice) + channel.voices.push(voice) + channel.voices[channel.voices.length-1].state = Voice.TRIGGER_ATTACK + const voiceId = channel.voices[channel.voices.length-1].id + this.#view.path = [this.#view.path[0], voiceId] + } + if (e.detail.action === "duplicate-channel") { + const channel = clone(this.#session.findChannel(this.#view.path[0]), true) + resetChannel(channel) + this.#session.channels.push(channel) + + const channelId = this.#session.channels[this.#session.channels.length-1].id + this.#view.path = [channelId] + } + if (e.detail.action === "delete-voice") { + + const channel = this.#session.findChannel(this.#view.path[0]) + const voice = channel.findVoice(this.#view.path[1]) + voice.state = Voice.TRIGGER_DELETE + + } + if (e.detail.action === "delete-channel") { + + const channel = this.#session.findChannel(this.#view.path[0]) + channel.state = Channel.TRIGGER_RELEASE + + } + this.dispatchEvent( + new CustomEvent( + ViewNavigation.UP, + { + detail: children.indexOf(e.detail), + bubbles: true, + composed: true + } + ) + ) + } + + set session(value) { + this.#session = value + } + + get session() { + return this.#session + } + + set view(value) { + this.#view = value + } + + get view() { + return this.#view + } + + set mode(value) { + this.#mode = value + this.dispatchEvent( new CustomEvent( + ViewNavigation.MODE, + { + detail: this.#mode, + composed: true + } + )) + this.addToRenderQueue(this.binding(this.#render)) + } + + get mode() { + return this.#mode + } + + set active(index) { + const children = Array.from(this.#container.children) + for(let i = 0; i < children.length; i++) { + children[i].active = (i == index) + } + } + + get active() { + const children = Array.from(this.#container.children) + for(let i = 0; i < children.length; i++) { + if (children[i].active) return i + } + return -1 + } + + #onSessionChange(signal) { + if (signal.path[0].property === "phase") return + this.addToRenderQueue(this.binding(this.#render)) + + } + + #onViewChange(signal) { + if (signal.path.length > 1) return + this.addToRenderQueue(this.binding(this.#render)) + } + + #getOscillatorFooter(oscillator) { + const f = [] + if (oscillator.am) f.push('A') + if (oscillator.fm) f.push('F') + if (oscillator.transpose) f.push('P') + if (oscillator.em) f.push('E') + if (oscillator.sx) f.push('S') + if (oscillator.gain) f.push('G') + return f.join("") + } + + #getOscillatorName(oscillator) { + switch (oscillator) { + case "am": + return "AM" + case "fm": + return "FM" + case "transpose": + return "Pitch" + case "em": + return "Exponent" + case "sx": + return "Scale" + case "gain": + default: + return "Gain" + } + } + + #getVoiceFooter(voice) { + return this.#getOscillatorFooter(voice.oscillator) + } + + #render() { + const rows = [] + const actionList = {items:[]} + if (this.#session && this.#view) { + + const showSiblings = this.#session.navigationMode === Session.SIBLINGS + const validPath = this.#session.getValidSubpath(this.#view.path) + + if (this.#view.navigationCollapsed) { + if (validPath.length == 0) { + actionList.items.push({header: "Session", footer: `${this.#session.channels.length}`, action: "toggle-collapse", label: this.#session.name, mode: "active", invisible: false, wrap: false}) + } else if (validPath.length == 1) { + let activeChannel = this.#session.findChannel(validPath[0]) + actionList.items.push({header: "Channel", footer: `${activeChannel.voices.length}`, action: "toggle-collapse", label: activeChannel.name, mode: "active", id: activeChannel.id, invisible: false, wrap: false}) + } else if (validPath.length == 2) { + let activeChannel = this.#session.findChannel(validPath[0]) + let activeVoice = activeChannel.findVoice(validPath[1]) + actionList.items.push({header: "Voice", footer: this.#getVoiceFooter(activeVoice), action: "toggle-collapse", label: activeVoice.name, mode: "active", id:activeVoice.id, invisible: false, wrap: false}) + } else if (validPath.length > 2) { + let ref = this.#session.getPathReference(validPath) + + let type = validPath[validPath.length-1].toUpperCase() + actionList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref), action: "toggle-collapse", label: type, mode: "active", id:validPath[validPath.length-1], invisible: false, wrap: false}) + } + } else { + if (this.#mode === NAVIGATE) { + let sessionList = {items:[]} + + // Session + if (validPath.length == 0) { + sessionList.items.push({header: "Session", mode: "active", footer: `${this.#session.channels.length}`, action: "toggle-collapse", label: this.#session.name, invisible: false, wrap: false}) + } else { + sessionList.items.push({header: "Session", mode: "path", footer: `${this.#session.channels.length}`, action: "session", label: this.#session.name, mode: "path", invisible: false, wrap: false}) + } + + // Channels + if (validPath.length == 0) { + this.#session.channels.forEach(channel=>{ + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "default", id: channel.id, invisible: false, wrap: false}) + }) + } else if (validPath.length == 1) { + this.#session.channels.forEach(channel=>{ + if (validPath[0] === channel.id) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "toggle-collapse", label: channel.name, mode: "active", id: channel.id, invisible: false, wrap: false}) + } else if (showSiblings) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "default", id: channel.id, invisible: false, wrap: false}) + } + }) + } else { + this.#session.channels.forEach(channel=>{ + if (validPath[0] === channel.id) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "path", id: channel.id, invisible: false, wrap: false}) + } else if (showSiblings) { + sessionList.items.push({header: "Channel", footer: `${channel.voices.length}`, action: "channel", label: channel.name, mode: "default", id: channel.id, invisible: false, wrap: false}) + + } + }) + } + if (sessionList.items.length) rows.push(sessionList) + + // Voices + let voiceList = {items:[]} + if (validPath.length >= 1) { + let activeChannel = this.#session.findChannel(validPath[0]) + activeChannel.voices.forEach(voice=>{ + if (validPath.length == 2 && validPath[1] === voice.id) { + voiceList.items.push({header: "Voice", footer: this.#getVoiceFooter(voice), action: "toggle-collapse", label: voice.name, mode: "active", id: voice.id, invisible: false, wrap: false}) + } else if (validPath.length > 2 && validPath[1] === voice.id) { + voiceList.items.push({header: "Voice", footer: this.#getVoiceFooter(voice), action: "voice", label: voice.name, mode: "path", id: voice.id, invisible: false, wrap: false}) + } else if (showSiblings || validPath.length == 1) { + voiceList.items.push({header: "Voice", footer: this.#getVoiceFooter(voice), action: "voice", label: voice.name, mode: "default", id: voice.id, invisible: false, wrap: false}) + } + }) + } + if (voiceList.items.length) rows.push(voiceList) + + // Oscillators + let oscillatorOrder = ["gain", "am", "fm", "transpose", "em", "sx"] + let oscillatorInsertPossible = false + if (validPath.length >= 2) { + let p = [] + + for (let i = 0; i < validPath.length; i++) { + p.push(validPath[i]) + const ref = this.#session.getPathReference(p) + if (i>=1) { + let oscillatorCount = 0 + let oscillatorList = {items:[]} + oscillatorOrder.forEach(name=>{ + const active = (i == validPath.length-2) && name === validPath[i+1] + const ispath = (i < validPath.length-2) && name === validPath[i+1] + if (ref[name]) { + oscillatorCount++ + const oscName = this.#getOscillatorName(name) + if (active) { + oscillatorList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref[name]), action: "toggle-collapse", label: oscName, mode: "active", path: [...p, name], invisible: false, wrap: false}) + } else if (ispath) { + oscillatorList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref[name]), action: "select-oscillator", label: oscName, mode: "path", id: name, path: [...p, name], invisible: false, wrap: false}) + } else if (showSiblings || i == validPath.length-1) { + oscillatorList.items.push({header: "Oscillator", footer: this.#getOscillatorFooter(ref[name]), action: "select-oscillator", label: oscName, mode: "default", id: name, path: [...p, name], invisible: false, wrap: false}) + } + } + + }) + if (oscillatorList.items.length != oscillatorOrder.length) oscillatorInsertPossible = true + if (oscillatorList.items.length) rows.push(oscillatorList) + } + } + + } + + // Actions + if (validPath.length == 0) { + actionList.items.push({header: "Channel", footer: "", action:"add-channel", label: "Add", mode: "insert", invisible: false, wrap: false}) + } else if (validPath.length == 1) { + let activeChannel = this.#session.findChannel(validPath[0]) + actionList.items.push({header: "Voice", footer: "", action:"add-voice", label: "Add", mode: "insert", invisible: false, wrap: false}) + actionList.items.push({header: "Channel", footer: activeChannel.name, action: "duplicate-channel", label: "Duplicate", mode: "insert", id: validPath[0], invisible: false, wrap: false}) + actionList.items.push({header: "Channel", footer: activeChannel.name, action: "delete-channel", label: "Delete", mode: "delete", id: validPath[0], invisible: false, wrap: false}) + } else if (validPath.length == 2) { + let activeChannel = this.#session.findChannel(validPath[0]) + let activeVoice + if (activeChannel) activeVoice = activeChannel.findVoice(validPath[1]) + if (oscillatorInsertPossible) actionList.items.push({header: "Oscillator", footer: "", action: "choose-oscillator", label: "Add", mode: "insert", invisible: false, wrap: false}) + actionList.items.push({header: "Voice", footer: activeVoice.name, action: "duplicate-voice", label: "Duplicate", mode: "insert", id: validPath[1], invisible: false, wrap: false}) + actionList.items.push({header: "Voice", footer: activeVoice.name, action: "delete-voice", label: "Delete", mode: "delete", id: validPath[1], invisible: false, wrap: false}) + } else if (validPath.length > 2) { + if (oscillatorInsertPossible) actionList.items.push({header: "Oscillator", footer: "", action: "choose-oscillator", label: "Add", mode: "insert", invisible: false, wrap: false}) + actionList.items.push({header: "Oscillator", footer: "", action: "delete-oscillator", label: "Delete", mode: "delete", id: validPath[validPath.length-1], invisible: false, wrap: false}) + } + } else if (this.#mode === INSERT_OSCILLATOR) { + let activeChannel = this.#session.findChannel(validPath[0]) + let activeVoice + if (activeChannel) activeVoice = activeChannel.findVoice(validPath[1]) + if (activeVoice) { + if (validPath.length == 2) actionList.items.push({header: "Oscillator", footer: "Cancel", action: "voice", label: "Cancel", mode: "active", id:activeVoice.id}) + else actionList.items.push({header: "Oscillator", footer: "Cancel", action: "select-oscillator", label: "Cancel", mode: "active", path: validPath}) + } + let ref = this.#session.getPathReference(validPath) + if (!ref.gain) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Gain", mode: "insert", id:"gain", path: [...validPath, "gain"]}) + if (!ref.am) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "AM", mode: "insert", id:"am", path: [...validPath, "am"]}) + if (!ref.fm) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "FM", mode: "insert", id:"fm", path: [...validPath, "fm"]}) + if (!ref.transpose) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Pitch", mode: "insert", id:"transpose", path: [...validPath, "transpose"]}) + if (!ref.em) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Exponent", mode: "insert", id:"em", path: [...validPath, "em"]}) + if (!ref.sx) actionList.items.push({header: "Oscillator", footer: "", action: "add-oscillator", label: "Scale", mode: "insert", id:"sx", path: [...validPath, "sx"]}) + + } + } + } + + if (actionList.items.length) rows.push(actionList) + + if (this.#session && this.#session.navigationMode === Session.COMPACT) this.#container.classList.add("force-row") + else this.#container.classList.remove("force-row") + updateUIList(this.#container, ButtonList, rows) + } + + destroy() { + super.destroy() + } +} \ No newline at end of file diff --git a/src/component/voice-editor.css b/src/component/voice-editor.css new file mode 100644 index 0000000..57d5ccd --- /dev/null +++ b/src/component/voice-editor.css @@ -0,0 +1,32 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: row; + flex-wrap: wrap; + gap: 6px; +} + +.content { + display: flex; + flex-direction: column; +} + +.hidden { + display: none; +} + +.row { + max-width: 100%; + display: flex; + flex-direction: row; + flex-wrap: wrap; + +} +canvas { + display:flex; +} \ No newline at end of file diff --git a/src/component/voice-editor.js b/src/component/voice-editor.js new file mode 100644 index 0000000..e6ee5f4 --- /dev/null +++ b/src/component/voice-editor.js @@ -0,0 +1,194 @@ + +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import Component from "./component.js" +import WaveSplineEditor from "./wave-spline-editor.js" +import Voice from "../model/voice.js" +import RotaryGroup from "./rotary-group.js" +import TimeDriver from "./rotary-driver/time-driver.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import beautifyTime from "../music/beautify-time.js" +import Button from "./button.js" + +export default class VoiceEditor extends Component { + + static ZERO = 'zero' + static KILL = 'kill' + static CHANGE = 'change' + static SOLO = 'solo' + static style = 'component/voice-editor.css' + + #content = document.createElement('div') + + #waveSplineEditor = WaveSplineEditor.create() + + #stateToggle = Button.create() + #zeroButton = Button.create() + #soloToggle = Button.create() + #gainRotary = RotaryGroup.create() + #attackEditor = RotaryGroup.create() // RampEditor.create() + #releaseEditor = RotaryGroup.create()// RampEditor.create() + + #voice + + constructor() { + super() + this.intitialized = false + + this.#soloToggle.header = "Bus" + this.#soloToggle.mode = "toggle" + this.shadowRoot.append(this.#soloToggle) + this.#soloToggle.addEventListener(Button.UP, this.binding(this.#onSoloToggle)) + + this.#stateToggle.header = "State" + this.#stateToggle.mode = "toggle" + this.shadowRoot.append(this.#stateToggle) + this.#stateToggle.addEventListener(Button.UP, this.binding(this.#onStateToggle)) + + this.#zeroButton.header = "Phase" + this.#zeroButton.label = "zero" + this.#zeroButton.mode = "toggle" + this.shadowRoot.append(this.#zeroButton) + this.#zeroButton.addEventListener(Button.UP, this.binding(this.#onZeroClick)) + + this.#gainRotary.drivers = [ + new GainDriver({name: "Gain"}) + ] + this.shadowRoot.append(this.#gainRotary) + this.#gainRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGainChange)) + + this.#attackEditor.drivers = [ + new TimeDriver({name: "Attack"}) + ] + this.shadowRoot.append(this.#attackEditor) + this.#attackEditor.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onAttackChange)) + + this.#releaseEditor.header = "Release" + this.#releaseEditor.drivers = [ + new TimeDriver({name: "Release"}) + ] + + this.#releaseEditor.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onReleaseChange)) + this.shadowRoot.append(this.#releaseEditor) + + this.#waveSplineEditor.zero = 0.5 + this.#waveSplineEditor.minYLabel = -1 + this.#waveSplineEditor.maxYLabel = 1 + this.shadowRoot.append(this.#waveSplineEditor) + watch(this, "voice", this.binding(this.#onVoiceChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(VoiceEditor.style) + this.intitialized = true + this.#update() + this.#updateTime() + } + + #onZeroClick(e) { + this.dispatchEvent( + new CustomEvent( + VoiceEditor.ZERO, + { + composed: true, + detail: this.#voice.id + } + ) + ) + } + + #onGainChange(e) { + this.#voice.gain = this.#gainRotary.value + } + + #onAttackChange(e) { + this.#voice.attack = this.#attackEditor.value + } + + #onReleaseChange(e) { + this.#voice.release = this.#releaseEditor.value + + } + + #onSoloToggle(e) { + this.dispatchEvent( + new CustomEvent( + VoiceEditor.SOLO, + { + detail: this.#voice.id, + composed: true + } + ) + ) + } + + #onStateToggle(e) { + if ( + this.#voice.state === Voice.ATTACK + || this.#voice.state === Voice.SUSTAIN + ) { + this.#voice.state = Voice.TRIGGER_RELEASE + } else if ( + this.#voice.state === Voice.RELEASE + || this.#voice.state === Voice.IDLE + ) { + this.#voice.state = Voice.TRIGGER_ATTACK + } + } + + get voice() { + return this.#voice + } + + set voice(value) { + this.#voice = value + } + + set settings(value) { + this.#waveSplineEditor.settings = value + } + + #onVoiceChange(signal) { + if (signal.path[0].property === "phase") return + if (signal.path.length == 1) this.#update() + if (signal.path.length >= 2) this.#updateTime() + + } + + #updateTime() { + const time = beautifyTime(this.#voice.oscillator.length * this.#voice.oscillator.wave.viewZoom) + this.#waveSplineEditor.maxXLabel = `${time.value} ${time.unit}` + } + + #update() { + if (this.#voice) { + if (this.#voice.bus === "solo") { + this.#soloToggle.label = "solo" + this.#soloToggle.mode = "solo" + } else { + this.#soloToggle.label = "mix" + this.#soloToggle.mode = "toggle" + } + this.#stateToggle.label = this.#voice.state + //this.#oscillatorEditor.path = this.#voice.path + this.#waveSplineEditor.waveSplineOscillator = this.#voice.oscillator + + this.#gainRotary.value = this.#voice.gain + this.#attackEditor.value = this.#voice.attack + this.#releaseEditor.value = this.#voice.release + this.#content.classList.remove("hidden") + } else { + this.#content.classList.add("hidden") + } + } + + destroy() { + unwatch(this, "voice") + this.#waveSplineEditor.destroy() + this.#attackEditor.destroy() + this.#releaseEditor.destroy() + super.destroy() + } + +} \ No newline at end of file diff --git a/src/component/wave-spline-editor.css b/src/component/wave-spline-editor.css new file mode 100644 index 0000000..f4ef18d --- /dev/null +++ b/src/component/wave-spline-editor.css @@ -0,0 +1,29 @@ +:host { + user-select: none; + display: flex; + min-width: 72px; + min-height: 72px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + max-width: 100%; + gap: 6px; +} + +.settings-container { + flex-direction: row; + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.wave-spline-container { + height: 72px; + flex: 1; +} + + +canvas { + display:flex; +} \ No newline at end of file diff --git a/src/component/wave-spline-editor.js b/src/component/wave-spline-editor.js new file mode 100644 index 0000000..3c74d4f --- /dev/null +++ b/src/component/wave-spline-editor.js @@ -0,0 +1,308 @@ +import watch from "../glue/watch.js" +import Component from "./component.js" +import Button from "./button.js" +import BarDriver from "./rotary-driver/bar-driver.js" +import ExponentDriver from "./rotary-driver/exponent-driver.js" +import FractionDriver from "./rotary-driver/fraction-driver.js" +import FrequencyDriver from "./rotary-driver/frequency-driver.js" +import GainDriver from "./rotary-driver/gain-driver.js" +import GridDriver from "./rotary-driver/grid-driver.js" +import NoteDriver from "./rotary-driver/note-driver.js" +import QuantizeDriver from "./rotary-driver/quantize-driver.js" +import TimeDriver from "./rotary-driver/time-driver.js" +import RotaryGroup from "./rotary-group.js" +import WaveSplineGraph from "./wave-spline-graph.js" + +export default class WaveSplineEditor extends Component { + + static CHANGE = 'change' + static style = 'component/wave-spline-editor.css' + + #waveSplineOscillator + #waveSplineGraph = WaveSplineGraph.create() + + #container = document.createElement('div') + #viewContainer = document.createElement('div') + #waveSplineContainer = document.createElement('div') + #tempoLock = Button.create() + #frequency = RotaryGroup.create() + #exponentRotary = RotaryGroup.create() + #phaseShiftRotary = RotaryGroup.create() + #transformCenterRotary = RotaryGroup.create() + #transformRangeRotary = RotaryGroup.create() + #viewZoomRotary = RotaryGroup.create() + #viewPositionRotary = RotaryGroup.create() + #quantizeXRotary = RotaryGroup.create() + #quantizeYRotary = RotaryGroup.create() + #gridXRotary = RotaryGroup.create() + #gridYRotary = RotaryGroup.create() + #settings + + #frequencyFractionDriver = new FractionDriver() + #frequencyBarDriver = new BarDriver() + + constructor() { + super() + this.intitialized = false + this.#frequency.drivers = [ + new FrequencyDriver(), + new NoteDriver(), + new TimeDriver(), + this.#frequencyFractionDriver, + this.#frequencyBarDriver + ] + + this.#exponentRotary.drivers = [ + new ExponentDriver() + ] + this.#phaseShiftRotary.drivers = [ + new GainDriver({name: "Phase offset"}) + ] + this.#viewZoomRotary.drivers = [ + new GainDriver({name: "View Zoom"}) + ] + this.#viewPositionRotary.drivers = [ + new GainDriver({name: "View Position"}) + ] + + this.#transformCenterRotary.drivers = [ + new GainDriver({name:"Scale Center"}) + ] + this.#transformRangeRotary.drivers = [ + new GainDriver({name:"Scale Range"}) + ] + this.#gridXRotary.drivers = [ + new GridDriver({name:"Horizontal Grid"}) + ] + this.#gridYRotary.drivers = [ + new GridDriver({name:"Vertical Grid"}) + ] + this.#quantizeXRotary.drivers = [ + new QuantizeDriver({name:"Quantize Time"}) + ] + this.#quantizeYRotary.drivers = [ + new QuantizeDriver({name:"Quantize Amplitude"}) + ] + + this.#viewContainer.classList.add("settings-container") + this.#viewContainer.append(this.#viewZoomRotary) + this.#viewContainer.append(this.#viewPositionRotary) + this.#viewContainer.append(this.#gridXRotary) + this.#viewContainer.append(this.#gridYRotary) + this.shadowRoot.append(this.#viewContainer) + + this.#waveSplineContainer.classList.add("wave-spline-container") + this.#waveSplineContainer.append(this.#waveSplineGraph) + this.shadowRoot.append(this.#waveSplineContainer) + + this.#container.classList.add("settings-container") + this.shadowRoot.append(this.#container) + + this.#tempoLock.header = "Tempo" + this.#tempoLock.label = "Sync" + this.#tempoLock.footer = "" + this.#tempoLock.mode = "toggle" + this.#tempoLock.addEventListener(Button.UP, this.binding(this.#onTempoLockClick)) + this.#container.append(this.#tempoLock) + + this.#container.append(this.#frequency) + + this.#container.append(this.#exponentRotary) + this.#container.append(this.#transformCenterRotary) + this.#container.append(this.#transformRangeRotary) + + this.#container.append(this.#phaseShiftRotary) + + this.#container.append(this.#quantizeXRotary) + this.#container.append(this.#quantizeYRotary) + + this.#frequency.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onFrequencyChange)) + this.#frequency.addEventListener(RotaryGroup.DRIVER_CHANGE, this.binding(this.#onFrequencyDriverChange)) + + this.#transformCenterRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onTransformCenterChange)) + this.#transformRangeRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onTransformRangeChange)) + + this.#exponentRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onExponentRotaryChange)) + this.#phaseShiftRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onPhaseShiftChange)) + this.#viewZoomRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onViewZoomChange)) + this.#viewPositionRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onViewPositionChange)) + this.#quantizeXRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onQuantizeXRotaryChange)) + this.#quantizeYRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onQuantizeYRotaryChange)) + this.#gridXRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGridXRotaryChange)) + this.#gridYRotary.addEventListener(RotaryGroup.CHANGE, this.binding(this.#onGridYRotaryChange)) + watch(this, "waveSplineOscillator", this.binding(this.#onWaveSplineOscillatorChange)) + watch(this, "settings", this.binding(this.#onSettingsChange)) + this.#init() + } + + async #init() { + await this.appendStyleLink(WaveSplineEditor.style) + this.intitialized = true + } + + #onTempoLockClick(e) { + this.#waveSplineOscillator.tempoSync = !this.#waveSplineOscillator.tempoSync + } + + #onFrequencyChange(e) { + this.#waveSplineOscillator.length = this.#frequency.value + } + + #onTransformCenterChange(e) { + this.#waveSplineOscillator.wave.transformCenter.x = this.#transformCenterRotary.value + } + + #onTransformRangeChange(e) { + this.#waveSplineOscillator.wave.transformRange.x = this.#transformRangeRotary.value + } + + #onPhaseShiftChange(e) { + this.#waveSplineOscillator.phaseShift = this.#phaseShiftRotary.value + } + + #onViewZoomChange(e) { + this.#waveSplineOscillator.wave.viewZoom = this.#viewZoomRotary.value + } + + #onViewPositionChange(e) { + this.#waveSplineOscillator.wave.viewPosition = this.#viewPositionRotary.value + } + + #onFrequencyDriverChange(e) { + this.#waveSplineOscillator.lengthDriver = this.#frequency.driver + } + + #onExponentRotaryChange(e) { + this.#waveSplineOscillator.wave.e = this.#exponentRotary.value + } + + #onQuantizeXRotaryChange(e) { + this.#waveSplineOscillator.wave.quantizeX = this.#quantizeXRotary.value + } + + #onQuantizeYRotaryChange(e) { + this.#waveSplineOscillator.wave.quantizeY = this.#quantizeYRotary.value + } + + #onGridXRotaryChange(e) { + this.#waveSplineOscillator.wave.gridX = this.#gridXRotary.value + } + + #onGridYRotaryChange(e) { + this.#waveSplineOscillator.wave.gridY = this.#gridYRotary.value + } + + set zero(value) { + this.#waveSplineGraph.zero = value + } + + get zero() { + return this.#waveSplineGraph.zero + } + + set minYLabel(value) { + this.#waveSplineGraph.minYLabel = value + } + + get minYLabel() { + return this.#waveSplineGraph.minYLabel + } + + set maxYLabel(value) { + this.#waveSplineGraph.maxYLabel = value + } + + get maxYLabel() { + return this.#waveSplineGraph.maxYLabel + } + + set maxXLabel(value) { + this.#waveSplineGraph.maxXLabel = value + } + + get maxXLabel() { + return this.#waveSplineGraph.maxXLabel + } + + set waveSplineOscillator(value) { + this.#waveSplineOscillator = value + } + + get waveSplineOscillator() { + return this.#waveSplineOscillator + } + + set settings(value) { + this.#settings = value + } + + get settings() { + return this.#settings + } + + #onSettingsChange(signal) { + this.#frequencyBarDriver.tempo = this.#settings.tempo + this.#frequencyFractionDriver.tempo = this.#settings.tempo + this.#update() + } + + #onWaveSplineOscillatorChange(signal) { + if (signal.path[0].property === "phase") this.#updatePlayhead() + else this.#update() + } + + #updatePlayhead() { + + if (this.#waveSplineOscillator.length > 0.5 ) { + this.#waveSplineGraph.playhead = (this.#waveSplineOscillator.phase + this.#waveSplineOscillator.phaseShift) % 1 + } else { + this.#waveSplineGraph.playhead = -1 + } + + } + + #update() { + if (this.#waveSplineOscillator && this.#waveSplineOscillator.wave) { + + this.#tempoLock.label = this.#waveSplineOscillator.tempoSync ? "Sync":"Free" + + this.#frequency.value = this.#waveSplineOscillator.length + this.#frequency.driver = this.#waveSplineOscillator.lengthDriver + this.#waveSplineGraph.waveSpline = this.#waveSplineOscillator.wave + this.#exponentRotary.value = this.#waveSplineOscillator.wave.e + this.#phaseShiftRotary.value = this.#waveSplineOscillator.phaseShift + this.#viewZoomRotary.value = this.#waveSplineOscillator.wave.viewZoom + + this.#viewPositionRotary.value = this.#waveSplineOscillator.wave.viewPosition + this.#transformCenterRotary.value = this.#waveSplineOscillator.wave.transformCenter.x + this.#transformRangeRotary.value = this.#waveSplineOscillator.wave.transformRange.x + this.#quantizeXRotary.value = this.#waveSplineOscillator.wave.quantizeX + this.#quantizeYRotary.value = this.#waveSplineOscillator.wave.quantizeY + this.#gridXRotary.value = this.#waveSplineOscillator.wave.gridX + this.#gridYRotary.value = this.#waveSplineOscillator.wave.gridY + + this.addToRenderQueue(this.binding(this.#updateDOM)) + } + + } + #updateDOM() { + if (this.#waveSplineOscillator.wave.viewZoom == 1 && this.#viewPositionRotary.parentElement) { + this.#viewPositionRotary.remove() + } else if (this.#waveSplineOscillator.wave.viewZoom != 1 && !this.#viewPositionRotary.parentElement) { + this.#viewContainer.insertBefore(this.#viewPositionRotary,this.#gridXRotary) + } + + if (!this.#waveSplineOscillator.sx && this.#transformCenterRotary.parentElement) { + this.#transformCenterRotary.remove() + } else if (this.#waveSplineOscillator.sx && !this.#transformCenterRotary.parentElement) { + this.#container.insertBefore(this.#transformCenterRotary, this.#quantizeXRotary) + } + + if (!this.#waveSplineOscillator.sx && this.#transformRangeRotary.parentElement) { + this.#transformRangeRotary.remove() + } else if (this.#waveSplineOscillator.sx && !this.#transformRangeRotary.parentElement) { + this.#container.insertBefore(this.#transformRangeRotary, this.#quantizeXRotary) + } + + } +} \ No newline at end of file diff --git a/src/component/wave-spline-graph.css b/src/component/wave-spline-graph.css new file mode 100644 index 0000000..0b0306d --- /dev/null +++ b/src/component/wave-spline-graph.css @@ -0,0 +1,41 @@ +:host { + font-family: sans-serif; + user-select: none; + display: flex; + min-width: 72px; + min-height: 228px; + padding-top: 6px; + padding-bottom: 6px; + white-space: nowrap; + overflow: hidden; + box-sizing: border-box; + flex-direction: column; + cursor: pointer; +} +canvas { + display:flex; + height: 204px; + touch-action: none; +} + +.header { + display: flex; + font-size: 9px; + margin-left: 6px; + margin-right: 6px; + min-height: 12px; + color: rgb(128,128,128); + flex-direction: row; + justify-content: space-between; +} + +.footer { + display: flex; + font-size: 9px; + margin-left: 6px; + margin-right: 6px; + min-height: 12px; + color: rgb(128,128,128); + flex-direction: row; + justify-content: space-between; +} diff --git a/src/component/wave-spline-graph.js b/src/component/wave-spline-graph.js new file mode 100644 index 0000000..89ed97e --- /dev/null +++ b/src/component/wave-spline-graph.js @@ -0,0 +1,597 @@ + +import hslToRgb from "../color/hsl-to-rgb.js" +import rgbaToCss from "../color/rgba-to-css.js" +import unwatch from "../glue/unwatch.js" +import watch from "../glue/watch.js" +import calculateDistance from "../math/calculate-distance.js" +import normalize from "../math/normalize.js" +import quantize from "../math/quantize.js" +import Point from "../model/point.js" +import findClosest from "../wave-spline/find-closest.js" +import solveWaveSpline from "../wave-spline/solve-wave-spline.js" +import Component from "./component.js" + +export default class WaveSplineGraph extends Component { + + static CHANGE = 'change' + static style = 'component/wave-spline-graph.css' + + #canvas = document.createElement('canvas') + #ctx + + #waveSpline// = new WaveSpline() + #horizontalPadding = 6 + #verticalPadding = 6 + #width + #height + #deepColor = hslToRgb({h: 0, s: 0, l: .25}) + #handleColor = hslToRgb({h: 0, s: 0, l: 1}) + #lineWidth = 2 + #gridWidth = 1 + #handleRadius = 3 + #zero = 0.5 + #minYLabel = "0" + #maxYLabel = "1" + #maxXLabel = "1" + #playhead = 0 + + #deleteThreshold = 20 + #selectionThreshold = 60 + #doubleTapDelay = 250 + #doubleTapDistance = 15 + + #lastTap = 0 + #lastTapPosition = new Point() + + #last = new Point() + + #selection = [] + + #innerWidth + #innerHeight + #top + #left + + #isDown + + #headerEl = document.createElement('div') + #maxXLabelEl = document.createElement('div') + #minYLabelEl = document.createElement('div') + #maxYLabelEl = document.createElement('div') + #footerEl = document.createElement('div') + + constructor() { + super() + this.intitialized = false + this.#canvas.setAttribute("draggable", false) + this.#canvas.setAttribute("width", 60) + this.#canvas.setAttribute("height", 60) + this.#ctx = this.#canvas.getContext("2d") + + this.observe(this.#canvas) + + this.#maxYLabelEl.classList.add("max-y") + this.#headerEl.append(this.#maxYLabelEl) + + this.#headerEl.classList.add("header") + this.shadowRoot.append(this.#headerEl) + + this.shadowRoot.append(this.#canvas) + + this.#minYLabelEl.classList.add("min-y") + this.#footerEl.append(this.#minYLabelEl) + + this.#maxXLabelEl.classList.add("max-x") + this.#footerEl.append(this.#maxXLabelEl) + + this.#footerEl.classList.add("footer") + this.shadowRoot.append(this.#footerEl) + + watch(this, "waveSpline", this.binding(this.#onWaveSplineChange)) + + this.#canvas.addEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.addEventListener("pointerup", this.binding(this.#onPointerUp)) + this.#canvas.addEventListener("pointercancel", this.binding(this.#onPointerCancel)) + this.#canvas.addEventListener("lostpointercapture", this.binding(this.#onPointerLost)) + + this.#updateValues() + this.#init() + } + + async #init() { + await this.appendStyleLink(WaveSplineGraph.style) + this.#calculate() + this.intitialized = true + } + + resize(contentRect) { + super.resize(contentRect) + this.#width = contentRect.width + this.#height = contentRect.height + this.#calculate() + } + + #onPointerDown(e) { + if (this.#isDown) return + if (e.button != 0) return + const now = Date.now() + if ( + now - this.#lastTap < this.#doubleTapDelay + && calculateDistance(this.#lastTapPosition, {x: e.clientX, y: e.clientY}) < this.#doubleTapDistance + ) { + this.#lastTap = 0 + this.#lastTapPosition.x = 0 + this.#lastTapPosition.y = 0 + this.#insertOrDelete(e) + } else { + this.#isDown = e.pointerId + this.#lastTap = Date.now() + this.#lastTapPosition.x = e.clientX + this.#lastTapPosition.y = e.clientY + this.#selectClosest(e) + if (this.#selection.length) { + this.#canvas.setPointerCapture(e.pointerId) + this.addEventListener("pointermove", this.binding(this.#onPointerMove)) + } + } + this.#last.x = e.clientX + this.#last.y = e.clientY + } + + #onPointerUp(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#canvas.releasePointerCapture(e.pointerId) + this.#positionFromEvent(e) + this.#endDrag(e) + } + + #onPointerCancel(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#canvas.releasePointerCapture(e.pointerId) + this.#endDrag(e) + } + + #onPointerLost(e) { + if (this.#isDown !== e.pointerId) return + this.#isDown = null + this.#canvas.releasePointerCapture(e.pointerId) + this.#endDrag(e) + } + + #onPointerMove(e) { + if (this.#isDown !== e.pointerId) return + this.#positionFromEvent(e) + } + + #endDrag(e) { + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + if(calculateDistance(this.#lastTapPosition, {x: e.clientX, y: e.clientY}) > 0) { + this.#alignToGrid(this.#selection) + } + } + + #waveSplineToDiagram(point) { + let from = Math.max(0, Math.min(1, this.#waveSpline.viewPosition * (1-this.#waveSpline.viewZoom))) + let range = this.#waveSpline.viewZoom + let to = from + range + return { + x: this.#innerWidth * ((point.x - from) / range), + y: this.#innerHeight * (1-point.y) + } + } + + #eventToWaveSpline(e) { + const p = this.#eventToDiagram(e) + + let from = Math.max(0, Math.min(1, this.#waveSpline.viewPosition * (1-this.#waveSpline.viewZoom))) + let range = this.#waveSpline.viewZoom + p.x = from + (p.x / this.#innerWidth) * range + p.y /= this.#innerHeight + p.y = 1-p.y + return p + } + + #eventToDiagram(e) { + const p = this.#eventToCanvas(e) + p.x -= this.#left + p.y -= this.#top + return p + } + + #eventToCanvas(e) { + const rect = this.#canvas.getBoundingClientRect() + return { + x: e.clientX - rect.left, + y: e.clientY - rect.top + } + } + + #insertOrDelete(e) { + const closest = this.#findClosest(e) + let insert = true + const dposition = this.#eventToDiagram(e) + if (closest) { + const point = this.#waveSplineToDiagram(closest) + const dist = calculateDistance(point, dposition) + if (dist < this.#deleteThreshold) { + insert = false + } + } + if (insert) { + const wposition = this.#alignPoint(this.#eventToWaveSpline(e)) + this.#waveSpline.points.push(wposition) + this.#waveSpline.sort() + } else if (closest) { + this.#waveSpline.points.splice(this.#waveSpline.points.indexOf(closest), 1) + } + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + } + + #findClosest(e) { + const wposition = this.#eventToWaveSpline(e) + return findClosest(wposition, this.#waveSpline.points, {x: this.#innerWidth / this.#waveSpline.viewZoom, y: this.#innerHeight}) + } + + #selectClosest(e) { + const closest = this.#findClosest(e) + let selected + if (closest) { + const distance = calculateDistance(this.#waveSplineToDiagram(closest), this.#eventToDiagram(e)) + if (distance < this.#selectionThreshold) { + selected = closest + } + + } + if (selected) this.#selection = [selected] + else this.#selection = [] + + } + + #alignPoint(point) { + point.x = quantize(point.x, this.#waveSpline.gridX, this.#waveSpline.gridXThreshold) + point.y = quantize(point.y, this.#waveSpline.gridY, this.#waveSpline.gridYThreshold) + return point + } + + + #alignToGrid(points) { + + points.forEach(point=>this.#alignPoint(point)) + this.#waveSpline.sort() + + } + + #positionFromEvent(e) { + let range = this.#waveSpline.viewZoom + + const dx = (e.clientX - this.#last.x) / (this.#innerWidth / range) + const dy = (e.clientY - this.#last.y) / -this.#innerHeight + + this.#last.x = e.clientX + this.#last.y = e.clientY + + this.#selection.forEach((point) => { + point.x = (point.x + dx + 1) % 1 + point.y = Math.min(1, Math.max(0, point.y + dy)) + }) + + this.#waveSpline.sort() + + this.dispatchEvent( + new CustomEvent( + WaveSplineGraph.CHANGE, + { + composed: true + } + ) + ) + } + + set playhead(value) { + if (this.#playhead === value) return + this.#playhead = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + get playhead() { + return this.#playhead + } + + set zero(value) { + this.#zero = value + this.addToRenderQueue(this.binding(this.#renderCanvas)) + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get zero() { + return this.#zero + } + + set maxYLabel(value) { + this.#maxYLabel = value + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get maxYLabel() { + return this.#maxYLabel + } + + set minYLabel(value) { + this.#minYLabel = value + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get minYLabel() { + return this.#minYLabel + } + + set maxXLabel(value) { + this.#maxXLabel = value + this.addToRenderQueue(this.binding(this.#updateValues)) + } + + get maxXLabel() { + return this.#maxXLabel + } + + set waveSpline(value) { + this.#waveSpline = value + } + + get waveSpline() { + return this.#waveSpline + } + + #onWaveSplineChange(signal) { + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #calculate() { + this.#innerWidth = this.#width - this.#horizontalPadding * 2 + this.#innerHeight = this.#height - this.#verticalPadding * 2 + this.#top = this.#verticalPadding + this.#left = this.#horizontalPadding + this.addToRenderQueue(this.binding(this.#renderCanvas)) + } + + #updateValues() { + this.#maxYLabelEl.textContent = this.#maxYLabel + this.#minYLabelEl.textContent = this.#minYLabel + this.#maxXLabelEl.textContent = this.#maxXLabel + } + + + #renderCanvas() { + if (this.#canvas.width != this.#width) this.#canvas.width = this.#width + if (this.#canvas.height != this.#height) this.#canvas.height = this.#height + + let oversampling = 2 + let p + + let from = Math.max(0, Math.min(1, this.#waveSpline.viewPosition * (1-this.#waveSpline.viewZoom))) + let range = this.#waveSpline.viewZoom + let to = from + range + + const wo = this.#innerWidth * oversampling + this.#ctx.clearRect(0, 0, this.#width, this.#height) + + + // zero + { + this.#ctx.save() + this.#ctx.strokeStyle = "#909090" + this.#ctx.lineWidth = this.#lineWidth/2 + const y = Math.round(this.#top + this.#innerHeight * (1-this.#zero)) + this.#ctx.beginPath() + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left + this.#innerWidth, y) + this.#ctx.stroke() + this.#ctx.restore() + + } + + // min + if (this.#zero > 0) { + this.#ctx.save() + this.#ctx.strokeStyle = "#303030" + this.#ctx.lineWidth = this.#lineWidth/2 + const y = this.#top + this.#innerHeight + this.#ctx.beginPath() + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left + this.#innerWidth, y) + this.#ctx.stroke() + this.#ctx.restore() + + } + + // max + if (this.#zero < 1) { + this.#ctx.save() + this.#ctx.strokeStyle = "#303030" + this.#ctx.lineWidth = this.#lineWidth/2 + const y = this.#top + this.#ctx.beginPath() + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left + this.#innerWidth, y) + this.#ctx.stroke() + this.#ctx.restore() + + } + + if (!this.#waveSpline) return + + this.#ctx.save() + + // horizontal grid + if ( + this.#waveSpline.gridX < Number.MAX_SAFE_INTEGER + ) { + const it = this.#innerWidth / this.#waveSpline.gridX / this.#waveSpline.viewZoom + for (let i = 0; i <= this.#waveSpline.gridX; i++) { + const x = Math.round( + this.#left + i * it - from * this.#innerWidth / this.#waveSpline.viewZoom + ) + if (x >= this.#left && x <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = "#303030" // rgbaToCss(this.#deepColor) + this.#ctx.lineWidth = this.#gridWidth + this.#ctx.moveTo(x, this.#top) + this.#ctx.lineTo(x, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + } + } + + // vertical grid + if ( + this.#waveSpline.gridY < Number.MAX_SAFE_INTEGER + ) { + const it = this.#innerHeight / this.#waveSpline.gridY + for (let i = 0; i <= this.#waveSpline.gridY; i++) { + const y = Math.round(this.#top + i * it) + this.#ctx.beginPath() + this.#ctx.strokeStyle = "#303030" // rgbaToCss(this.#deepColor) + this.#ctx.lineWidth = this.#gridWidth + this.#ctx.moveTo(this.#left, y) + this.#ctx.lineTo(this.#left+this.#innerWidth, y) + this.#ctx.stroke() + } + } + + // Transform range + this.#ctx.save() + const leftRange = Math.max( + this.#left, + this.#left + (this.#waveSpline.transformCenter.x - this.#waveSpline.transformRange.x) * this.#innerWidth/range + ) + if (leftRange >= this.#left && leftRange <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#003477' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.setLineDash([2,4]); + this.#ctx.moveTo(leftRange, this.#top) + this.#ctx.lineTo(leftRange, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + const rightRange = Math.min( + this.#left + this.#innerWidth, + this.#left + (this.#waveSpline.transformCenter.x + this.#waveSpline.transformRange.x) * this.#innerWidth/range + ) + if (rightRange >= this.#left && rightRange <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#003477' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.setLineDash([2,4]); + this.#ctx.moveTo(rightRange, this.#top) + this.#ctx.lineTo(rightRange, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + this.#ctx.restore() + + // Transform center + this.#ctx.save() + const scaleCenter = Math.max( + this.#left, + Math.min( + this.#left + this.#innerWidth, + this.#left + this.#waveSpline.transformCenter.x * this.#innerWidth/range + ) + ) + + if (scaleCenter >= this.#left && scaleCenter <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#003477' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.setLineDash([4,2]); + this.#ctx.moveTo(scaleCenter, this.#top) + this.#ctx.lineTo(scaleCenter, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + this.#ctx.restore() + + // quantized Wavespline + if ( + !this.#waveSpline.quantizeX < Number.MAX_SAFE_INTEGER || + !this.#waveSpline.quantizeY < Number.MAX_SAFE_INTEGER + ) { + // render quantized no oversampling + for (let x = 0; x < this.#innerWidth; x++) { + const px = x / this.#innerWidth + + let t = normalize(px, {min: from, max:to}) + + let y = solveWaveSpline(this.#waveSpline, t%1) + let c = {x: this.#left + x, y: y} + c.y = this.#top + normalize((1-c.y ), {max: this.#innerHeight}) + if (p) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = rgbaToCss(this.#deepColor) + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.moveTo(p.x, p.y) + this.#ctx.lineTo(c.x, c.y) + this.#ctx.stroke() + } + p = c + } + } + p = null + + // Wavespline + for (let x = 0; x < wo; x++) { + const px = x / wo + let t = normalize(px, {min: from, max:to}) + let y = solveWaveSpline(this.#waveSpline, t%1, 1, 1, 1, true) + let c = {x: this.#left + x / oversampling, y: y} + c.y = this.#top + normalize((1-c.y ), {max: this.#innerHeight}) + if (p) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = rgbaToCss(this.#handleColor) + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.moveTo(p.x, p.y) + this.#ctx.lineTo(c.x, c.y) + this.#ctx.stroke() + } + p = c + + } + this.#ctx.restore() + + // playhead + this.#ctx.save() + const playheadPos = this.#left + this.#playhead * this.#innerWidth/range + if (playheadPos >= this.#left && playheadPos <= this.#left+this.#innerWidth) { + this.#ctx.beginPath() + this.#ctx.strokeStyle = '#cc0000' + this.#ctx.lineWidth = this.#lineWidth + this.#ctx.moveTo(playheadPos, this.#top) + this.#ctx.lineTo(playheadPos, this.#top + this.#innerHeight) + this.#ctx.stroke() + } + this.#ctx.restore() + + // wavespline points + for (let i = 0; i < this.#waveSpline.points.length; i++) { + let s = this.#waveSpline.points[i] + let x = this.#left + (s.x - from) * this.#innerWidth/range + if (x >= this.#left && x <= this.#left+this.#innerWidth) { + this.#ctx.save() + this.#ctx.beginPath(); + this.#ctx.fillStyle = rgbaToCss(this.#handleColor) + this.#ctx.arc(x , this.#top + (1-s.y) * this.#innerHeight, this.#handleRadius, 0, 2 * Math.PI) + this.#ctx.fill() + this.#ctx.restore() + } + } + } + + destroy() { + unwatch(this) + this.#waveSpline = null + this.#canvas.removeEventListener("pointerdown", this.binding(this.#onPointerDown)) + this.#canvas.removeEventListener("pointermove", this.binding(this.#onPointerMove)) + this.#canvas.removeEventListener("pointerup", this.binding(this.#onPointerUp)) + super.destroy() + } +} \ No newline at end of file diff --git a/src/data/clone.js b/src/data/clone.js new file mode 100644 index 0000000..c9c015b --- /dev/null +++ b/src/data/clone.js @@ -0,0 +1,18 @@ +export default function clone(obj, anonymize = false) { + obj = JSON.parse(JSON.stringify(obj)) + if (anonymize) removeIds(obj) + return obj +} + +function removeIds(obj) { + if (!obj) return + if (Array.isArray(obj)) { + obj.forEach(removeIds) + } else if (typeof obj === "object") { + if (obj.id) delete obj.id + if (obj.name) delete obj.name + Object.values(obj).forEach(removeIds) + } + return obj + +} \ No newline at end of file diff --git a/src/data/generate-id.js b/src/data/generate-id.js new file mode 100644 index 0000000..5969281 --- /dev/null +++ b/src/data/generate-id.js @@ -0,0 +1,8 @@ +import generateUuidV4 from "./generate-uuid-v4.js" + +export default function generateId() { + // when crypto available + if (typeof crypto !== "undefined") return crypto.randomUUID() + // otherwise (Audio worklets seem to not support it) + return generateUuidV4() +} \ No newline at end of file diff --git a/src/data/generate-uuid-v4.js b/src/data/generate-uuid-v4.js new file mode 100644 index 0000000..c9f2473 --- /dev/null +++ b/src/data/generate-uuid-v4.js @@ -0,0 +1,6 @@ +export default function generateUuidV4() { + return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, (c) => { + const r = Math.floor(Math.random() * 16) + return r.toString(16) + }); +} \ No newline at end of file diff --git a/src/data/get-properties.js b/src/data/get-properties.js new file mode 100644 index 0000000..daf088f --- /dev/null +++ b/src/data/get-properties.js @@ -0,0 +1,9 @@ +export default function getProperties(instance, limit = Object) { + let properties = {} + const proto = Object.getPrototypeOf(instance) + Object.assign(properties, Object.getOwnPropertyDescriptors(proto)) + if (proto !== limit.prototype) { + return Object.assign(properties, getProperties(proto, limit)) + } + return properties +} \ No newline at end of file diff --git a/src/data/instance-from.js b/src/data/instance-from.js new file mode 100644 index 0000000..32d40e5 --- /dev/null +++ b/src/data/instance-from.js @@ -0,0 +1,5 @@ +export default function instanceFrom(cls, object) { + if (!object) return null + if (object instanceof cls) return object + return new cls(object) +} \ No newline at end of file diff --git a/src/data/make-enumerable.js b/src/data/make-enumerable.js new file mode 100644 index 0000000..d8f6ddb --- /dev/null +++ b/src/data/make-enumerable.js @@ -0,0 +1,11 @@ +import getProperties from "./get-properties.js"; + +export default function makeEnumerable(instance, cls) { + const properties = getProperties(instance, cls) + for (const descriptor in properties) { + if (properties[descriptor].get && properties[descriptor].set) { + properties[descriptor].enumerable = true + Object.defineProperty(instance, descriptor, {...properties[descriptor], enumerable: true}); + } + } +} \ No newline at end of file diff --git a/src/data/manage-typed-array.js b/src/data/manage-typed-array.js new file mode 100644 index 0000000..1f8e2df --- /dev/null +++ b/src/data/manage-typed-array.js @@ -0,0 +1,20 @@ +export default function manageTypedArray(host, cls, value) { + const existing = new Map() + for (let i = 0; i list.length) { + host.lastChild.destroy() + } + while (host.children.length < list.length) { + const comp = cls.create() + host.append(comp) + } + for (let i = 0; i { + if (value === boundSubclassGetter()) return // skip identical + boundSubclassSetter(value) + Signal.broadcast(instance, Signal.CHANGE, name) + }, + get: boundSubclassGetter, + configurable: true, + enumerable: true + } + Object.defineProperty(instance, name, proxyDescriptor) + } + } +} \ No newline at end of file diff --git a/src/glue/ensure-type.js b/src/glue/ensure-type.js new file mode 100644 index 0000000..5316206 --- /dev/null +++ b/src/glue/ensure-type.js @@ -0,0 +1,8 @@ +export default function ensureType(type, value) { + if (value === null || value === undefined) return null + if (value instanceof type) return value + if (type === String) return String(value) + if (type === Number) return Number(value) + if (type === Boolean) return !!value + return new type(value) +} \ No newline at end of file diff --git a/src/glue/ensure-types.js b/src/glue/ensure-types.js new file mode 100644 index 0000000..a3f30fc --- /dev/null +++ b/src/glue/ensure-types.js @@ -0,0 +1,5 @@ +import ensureType from "./ensure-type.js"; + +export default function ensureTypes(type, array) { + return array.map(element => ensureType(type, element)) +} \ No newline at end of file diff --git a/src/glue/signal.js b/src/glue/signal.js new file mode 100644 index 0000000..d8cb8a5 --- /dev/null +++ b/src/glue/signal.js @@ -0,0 +1,68 @@ +import Subscription from "./subscription.js" + +export default class Signal { + static DELAY = 0 + static queue = new Set() + static origin = new WeakMap() + static timeout + + static subscribe(origin, callback) { + if (!(callback instanceof Function)) throw new Error("Callback function required") + if (!Signal.origin.has(origin)) Signal.origin.set(origin, new Set()) + Signal.origin.get(origin).add(callback) + return new Subscription(origin, callback) + } + + static unsubscribe(origin, callback) { + if (Signal.origin.has(origin)) { + Signal.origin.get(origin).delete(callback) + if (!Signal.origin.get(origin).size) Signal.origin.delete(origin) + } + } + + static flush() { + for (let signal of Signal.queue) { + signal.callback(signal) + } + Signal.timeout = null + Signal.queue = new Set() + } + + static broadcast(origin, signal = {}) { + if (Signal.origin.has(origin)) { + for (const callback of Signal.origin.get(origin)) { + Signal.queue.add(new Signal({ + path: signal.path, + origin, + callback, + property: signal.property + })) + } + if (!Signal.timeout) Signal.timeout = setTimeout(Signal.flush, Signal.DELAY) + } + } + + #origin + #path + #callback + #property + constructor({origin = null, path = [], callback = ()=>{}, property=null} = {}) { + this.#origin = origin + this.#path = [...path, {origin, property}] + this.#property = property + this.#callback = callback + } + + get origin() { + return this.#origin + } + get path() { + return this.#path + } + get callback() { + return this.#callback + } + get property() { + return this.#property + } +} \ No newline at end of file diff --git a/src/glue/subscription.js b/src/glue/subscription.js new file mode 100644 index 0000000..afbcb62 --- /dev/null +++ b/src/glue/subscription.js @@ -0,0 +1,14 @@ +export default class Subscription { + #origin + #callback + constructor(origin, callback) { + this.#origin = origin + this.#callback = callback + } + get origin() { + return this.#origin + } + get callback() { + return this.#callback + } +} \ No newline at end of file diff --git a/src/glue/t-array.js b/src/glue/t-array.js new file mode 100644 index 0000000..52ad89f --- /dev/null +++ b/src/glue/t-array.js @@ -0,0 +1,128 @@ +import ensureType from "./ensure-type.js" +import ensureTypes from "./ensure-types.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +export default class TArray extends TProperty { + static MUTABLE = ["shift", "pop", "reverse", "sort", "copyWithin"] + #subscriptions = new Map() + #type + constructor(value, type) { + super() + this.#type = type + this.write(value) + } + + #updateSubscriptions() { + const active = new Set() + for (let i = 0; i < this.value.length; i++) { + active.add(this.value[i]) + if (!this.#subscriptions.has(this.value[i])) { + if (typeof this.value[i] === "object") { + const subscription = Signal.subscribe(this.value[i], (signal)=>{ + Signal.broadcast(this, signal) + }) + this.#subscriptions.set(this.value[i], subscription) + } + } + } + for (const [key, value] of this.#subscriptions.entries()) { + if (!active.has(key)) { + Signal.unsubscribe(value.origin, value.callback) + this.#subscriptions.delete(key) + } + } + } + + write(value) { + const type = this.#type + const updateSubscriptions = this.#updateSubscriptions.bind(this) + if (Array.isArray(value)) value = ensureTypes(type, value) + const reference = value + // proxy mutable methods + { + const method = reference.push + value.push = (...elements) => { + const result = method.apply( + reference, + ensureTypes(type, elements) + ) + Signal.broadcast(this) + updateSubscriptions() + return result + } + } + { + const method = reference.unshift + value.unshift = (...elements) => { + const result = method.apply( + reference, + ensureTypes(type, elements) + ) + updateSubscriptions() + return result + } + } + { + const method = reference.splice + value.splice = (start, deleteCount, ...elements) => { + const result = method.call( + reference, + start, + deleteCount, + ...ensureTypes(type, elements) + ) + Signal.broadcast(this) + updateSubscriptions() + return result + } + } + { + const method = reference.fill + value.fill = (element, start, end) => { + const result = method.call( + reference, + ensureType(element), + start, + end + ) + Signal.broadcast(this) + updateSubscriptions() + return result + } + } + TArray.MUTABLE.forEach((name)=>{ + const method = value[name] + reference[name] = (...args) => { + const result = method.call(reference, ...args) + Signal.broadcast(this) + updateSubscriptions() + return result + } + }) + const self = this + + // add dynamic numerical property proxy + value = new Proxy(value, { + set: function(target, property, value) { + if (property === 'length' || isNaN(property)) { + target[property] = value; + } else { + target[property] = ensureType(type, value) + Signal.broadcast(self) + updateSubscriptions() + } + return true + }, + deleteProperty: function(target, property) { + delete target[property]; + Signal.broadcast(self) + updateSubscriptions() + return true + } + }) + const returnValue = super.write(value) + updateSubscriptions() + return returnValue + } +} \ No newline at end of file diff --git a/src/glue/t-boolean.js b/src/glue/t-boolean.js new file mode 100644 index 0000000..0955ec9 --- /dev/null +++ b/src/glue/t-boolean.js @@ -0,0 +1,8 @@ +import TProperty from "./t-property.js" + +export default class TBoolean extends TProperty { + constructor(value) { + super() + this.write(!!value) + } +} \ No newline at end of file diff --git a/src/glue/t-instance.js b/src/glue/t-instance.js new file mode 100644 index 0000000..12fb8d3 --- /dev/null +++ b/src/glue/t-instance.js @@ -0,0 +1,24 @@ +import ensureType from "./ensure-type.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +export default class TInstance extends TProperty { + #type + #subscription + constructor(value, type) { + super() + this.#type = type + this.write(value) + } + + write(value) { + value = ensureType(this.#type, value) + if (this.#subscription) Signal.unsubscribe(this.#subscription.origin, this.#subscription.callback) + if (value) { + this.#subscription = Signal.subscribe(value, (signal)=>{ + Signal.broadcast(this, signal) + }) + } + return super.write(value) + } +} \ No newline at end of file diff --git a/src/glue/t-number.js b/src/glue/t-number.js new file mode 100644 index 0000000..cb95b19 --- /dev/null +++ b/src/glue/t-number.js @@ -0,0 +1,8 @@ +import TProperty from "./t-property.js" + +export default class TNumber extends TProperty { + constructor(value) { + super() + this.write(Number(value)) + } +} \ No newline at end of file diff --git a/src/glue/t-object.js b/src/glue/t-object.js new file mode 100644 index 0000000..cb695bd --- /dev/null +++ b/src/glue/t-object.js @@ -0,0 +1,62 @@ +import ensureType from "./ensure-type.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +export default class TObject extends TProperty { + #type = String + #subscriptions = new Map() + constructor(value, type) { + super() + this.#type = type + this.write(value) + } + + #updateSubscriptions() { + const active = new Set() + for (let key in this.value) { + active.add(key) + let item = this.value[key] + if (!this.#subscriptions.has(key)) { + if (typeof item === "object") { + const subscription = Signal.subscribe(item, (signal)=>{ + Signal.broadcast(this, signal) + }) + this.#subscriptions.set(key, subscription) + } + } + } + for (const [key, value] of this.#subscriptions.entries()) { + if (!active.has(key)) { + Signal.unsubscribe(value.origin, value.callback) + this.#subscriptions.delete(key) + } + } + } + + write(value) { + const map = value || {} + const type = this.#type + for (let [key, item] of Object.entries(value)) { + value[key] = ensureType(this.#type, item) + } + + const updateSubscriptions = this.#updateSubscriptions.bind(this) + const self = this + + const proxy = new Proxy(map, { + set: function(target, property, value) { + target[property] = ensureType(type, value) + Signal.broadcast(self) + updateSubscriptions() + return true + }, + deleteProperty: function(target, property) { + delete target[property] + Signal.broadcast(self) + updateSubscriptions() + return true + } + }) + return super.write(proxy) + } +} \ No newline at end of file diff --git a/src/glue/t-property.js b/src/glue/t-property.js new file mode 100644 index 0000000..70ef3db --- /dev/null +++ b/src/glue/t-property.js @@ -0,0 +1,24 @@ +export default class TProperty { + + #value + + constructor() { + + } + + write(value) { + this.value = value + } + + read() { + return this.value + } + + get value() { + return this.#value + } + + set value(value) { + return this.#value = value + } +} \ No newline at end of file diff --git a/src/glue/t-string.js b/src/glue/t-string.js new file mode 100644 index 0000000..caaff67 --- /dev/null +++ b/src/glue/t-string.js @@ -0,0 +1,8 @@ +import TProperty from "./t-property.js" + +export default class TString extends TProperty { + constructor(value) { + super() + this.write(String(value)) + } +} \ No newline at end of file diff --git a/src/glue/t.js b/src/glue/t.js new file mode 100644 index 0000000..e76751a --- /dev/null +++ b/src/glue/t.js @@ -0,0 +1,29 @@ +import TArray from "./t-array.js" +import TBoolean from "./t-boolean.js" +import TObject from "./t-object.js" +import TNumber from "./t-number.js" +import TInstance from "./t-instance.js" +import TString from "./t-string.js" + +const typeMap = new Map([ + [String, TString], + [Number, TNumber], + [Boolean, TBoolean] +]) + +export function T(type, value) { + if (typeMap.has(type)){ + return new (typeMap.get(type))(value) + } + return new TInstance(value, type) +} + +export function A(type, value) { + if (!Array.isArray(value)) value = [] + return new TArray(value, type) +} + +export function O(type, value) { + if (typeof value !== 'object') value = {} + return new TObject(value, type) +} \ No newline at end of file diff --git a/src/glue/unwatch.js b/src/glue/unwatch.js new file mode 100644 index 0000000..42723e1 --- /dev/null +++ b/src/glue/unwatch.js @@ -0,0 +1,18 @@ +import Signal from "./signal.js" +import { references } from "./watch.js" + +export default function unwatch(reference, name) { + if (!references.has(reference)) return + if (!name) { + for (let [name, subscription] of references.get(reference)) { + Signal.unsubscribe(subscription.origin, subscription.callback) + references.get(reference).delete(name) + if (!references.get(reference).size) references.delete(reference) + } + } else if (references.get(reference).has(name)){ + const subscription = references.get(reference).get(name) + Signal.unsubscribe(subscription.origin, subscription.callback) + references.get(reference).delete(name) + if (!references.get(reference).size) references.delete(reference) + } +} \ No newline at end of file diff --git a/src/glue/watch.js b/src/glue/watch.js new file mode 100644 index 0000000..377faef --- /dev/null +++ b/src/glue/watch.js @@ -0,0 +1,29 @@ +import getProperties from "../data/get-properties.js" +import Signal from "./signal.js" + +export const references = new Map() + +export default function watch(reference, name, callback) { + const properties = getProperties(reference) + if (!properties[name]) return + const descriptor = properties[name] + if (descriptor && descriptor.set) { + const setter = descriptor.set.bind(reference) + descriptor.set = (value) => { + if (references.has(reference) && references.get(reference).has(name)) { + const subscription = references.get(reference).get(name) + Signal.unsubscribe(subscription.origin, subscription.callback) + references.get(reference).delete(name) + if (!references.get(reference).size) references.delete(reference) + } + setter(value) + if (value) { + if (!references.has(reference)) references.set(reference, new Map()) + references.get(reference).set(name, Signal.subscribe(value, callback)) + } + callback(new Signal({origin: value, callback})) + } + Object.defineProperty(reference, name, descriptor) + } + +} \ No newline at end of file diff --git a/src/glue/wrap.js b/src/glue/wrap.js new file mode 100644 index 0000000..d221886 --- /dev/null +++ b/src/glue/wrap.js @@ -0,0 +1,55 @@ +import getProperties from "../data/get-properties.js" +import Signal from "./signal.js" +import TProperty from "./t-property.js" + +function wrapT(instance, name, descriptor) { + const reference = descriptor.get.apply(instance) + return { + ...descriptor, + set: (value)=> { + const before = reference.read() + reference.write(value) + if (before != reference.read()) Signal.broadcast(instance, {property: name}) + }, + get: () => { + return reference.read() + }, + configurable: false, + enumerable: true + } +} + +function wrapProperty(instance, name, descriptor) { + const setter = descriptor.set.bind(instance) + return { + ...descriptor, + set: (value)=> { + setter(value) + Signal.broadcast(instance, {property: name}) + }, + configurable: false, + enumerable: true + } +} + + +export default function wrap(instance) { + const properties = getProperties(instance) + for (let [name, descriptor] of Object.entries(properties)) { + if (descriptor.set && descriptor.get) { + const initialValue = descriptor.get.apply(instance) + if (initialValue instanceof TProperty) { + descriptor = wrapT(instance, name, descriptor) + Signal.subscribe(initialValue, (signal)=>{ + // tProperty is removed from path + Signal.broadcast(instance, {path: [...signal.path.slice(0,-1)], property: name}) + }) + } else { + descriptor = wrapProperty(instance, name, descriptor) + } + Object.defineProperty(instance, name, descriptor) + } + } + return instance + +} \ No newline at end of file diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000..c82e95c --- /dev/null +++ b/src/index.html @@ -0,0 +1,42 @@ + + + + + + + + AWSM - AwesomeWaveSplineMachine + + + + + + + + + + diff --git a/src/math/calculate-angle-between.js b/src/math/calculate-angle-between.js new file mode 100644 index 0000000..6a024dc --- /dev/null +++ b/src/math/calculate-angle-between.js @@ -0,0 +1,9 @@ +import wrapAngle from "./wrap-angle.js" +import { TAU } from "./contants.js" + +export default function calculateAngleBetween(a, b) { + a = wrapAngle(a) + b = wrapAngle(b) + const delta = (b - a + TAU) % TAU + return delta +} \ No newline at end of file diff --git a/src/math/calculate-angle.js b/src/math/calculate-angle.js new file mode 100644 index 0000000..8b6f00d --- /dev/null +++ b/src/math/calculate-angle.js @@ -0,0 +1,3 @@ +export default function calculateAngle({x = 0, y = 0}) { + return Math.atan2(y ,x); +} \ No newline at end of file diff --git a/src/math/calculate-circle-point.js b/src/math/calculate-circle-point.js new file mode 100644 index 0000000..308b4c9 --- /dev/null +++ b/src/math/calculate-circle-point.js @@ -0,0 +1,7 @@ + +export default function calculateCirclePoint(radius, angle) { + return { + x: radius * Math.cos(angle), + y: radius * Math.sin(angle) + } +} \ No newline at end of file diff --git a/src/math/calculate-distance.js b/src/math/calculate-distance.js new file mode 100644 index 0000000..e7e852a --- /dev/null +++ b/src/math/calculate-distance.js @@ -0,0 +1,5 @@ +export default function calculateDistance(a = {x: 0, y: 0}, b = {x: 0, y: 0}, weight = {x:1, y:1}) { + const dx = (b.x - a.x) * weight.x + const dy = (b.y - a.y) * weight.y + return Math.sqrt(dx * dx + dy * dy) +} \ No newline at end of file diff --git a/src/math/calculate-length.js b/src/math/calculate-length.js new file mode 100644 index 0000000..8b703c8 --- /dev/null +++ b/src/math/calculate-length.js @@ -0,0 +1,3 @@ +export default function calculateLength(a, b) { + return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)) +} \ No newline at end of file diff --git a/src/math/calculate-pole-value.js b/src/math/calculate-pole-value.js new file mode 100644 index 0000000..e30a6b4 --- /dev/null +++ b/src/math/calculate-pole-value.js @@ -0,0 +1,10 @@ +import Point from "../model/point.js" +import { TAU } from "./contants.js" +import rotatePoint from "./rotate-point.js" + +export default function calculatePoleValue(pole, poles, position) { + const segmentAngle = TAU / poles + let rotated = rotatePoint(new Point(), position, pole * segmentAngle ) + let len = Math.max(0, Math.min(1, (rotated.y+1)/2)) + return len +} \ No newline at end of file diff --git a/src/math/calculate-q.js b/src/math/calculate-q.js new file mode 100644 index 0000000..b426c6d --- /dev/null +++ b/src/math/calculate-q.js @@ -0,0 +1,5 @@ +export default function calcQ(a, b, x) { + const dx = (1 + (b - a)) % 1 + const xn = ((1 + (x - a)) % 1) / dx + return xn +} \ No newline at end of file diff --git a/src/math/compare-float.js b/src/math/compare-float.js new file mode 100644 index 0000000..d988af5 --- /dev/null +++ b/src/math/compare-float.js @@ -0,0 +1,3 @@ +export default function compareFloat(a,b, tolerance = 1e-8) { + return Math.abs(a - b) < tolerance +} \ No newline at end of file diff --git a/src/math/contants.js b/src/math/contants.js new file mode 100644 index 0000000..70a0622 --- /dev/null +++ b/src/math/contants.js @@ -0,0 +1 @@ +export const TAU = Math.PI * 2 \ No newline at end of file diff --git a/src/math/from-fraction.js b/src/math/from-fraction.js new file mode 100644 index 0000000..5f13869 --- /dev/null +++ b/src/math/from-fraction.js @@ -0,0 +1,11 @@ +export function fromFraction(str) { + const match = /([0-9]+)(\/([0-9]+))?/.exec(str) + let val = 1 + if (match.length) { + const num = parseInt(match[1]) + const denom = parseInt(match[3]) + if (!Number.isNaN(num)) val = num + if (!Number.isNaN(denom) && denom > 0) val /= denom + } + return val +} \ No newline at end of file diff --git a/src/math/interpolate-exponential.js b/src/math/interpolate-exponential.js new file mode 100644 index 0000000..11ce3b3 --- /dev/null +++ b/src/math/interpolate-exponential.js @@ -0,0 +1,7 @@ +import interpolateLinear from "./interpolate-linear.js" + +export default function interpolateExponential(a, b, e, q) { + if (e == 1) return interpolateLinear(a, b, q) // is linear + if (q < .5) return interpolateLinear(a, b, Math.pow((q * 2), e) / 2) + return interpolateLinear(a, b, 1 - Math.pow(((1 - q) * 2), e) / 2) +} \ No newline at end of file diff --git a/src/math/interpolate-linear.js b/src/math/interpolate-linear.js new file mode 100644 index 0000000..6cd3bd7 --- /dev/null +++ b/src/math/interpolate-linear.js @@ -0,0 +1,3 @@ +export default function interpolateLinear(a, b, q) { + return a + (b - a) * q; +} \ No newline at end of file diff --git a/src/math/interpolate-point.js b/src/math/interpolate-point.js new file mode 100644 index 0000000..f05811a --- /dev/null +++ b/src/math/interpolate-point.js @@ -0,0 +1,8 @@ +import interpolateLinear from "./interpolate-linear.js"; + +export default function interpolatePoint(a, b, q) { + return { + x: interpolateLinear(a.x, b.x, q), + y: interpolateLinear(a.y, b.y, q) + } +} \ No newline at end of file diff --git a/src/math/multiply-exponential-quotient.js b/src/math/multiply-exponential-quotient.js new file mode 100644 index 0000000..3406a0c --- /dev/null +++ b/src/math/multiply-exponential-quotient.js @@ -0,0 +1,3 @@ +export default function multiplyExponentialQuotient(x, {n=1, o=1} = {}) { + return x * Math.pow(2, n/o) +} \ No newline at end of file diff --git a/src/math/normalize.js b/src/math/normalize.js new file mode 100644 index 0000000..6a76077 --- /dev/null +++ b/src/math/normalize.js @@ -0,0 +1,3 @@ +export default function normalize(value, {min = 0, max = 1} = {}) { + return value * (max-min) + min +} \ No newline at end of file diff --git a/src/math/quantize.js b/src/math/quantize.js new file mode 100644 index 0000000..f7c3b01 --- /dev/null +++ b/src/math/quantize.js @@ -0,0 +1,5 @@ +export default function quantize(value, quantize = Number.MAX_SAFE_INTEGER, threshold = 0, override = false) { + if (override || quantize >= Number.MAX_SAFE_INTEGER) return value + let t = threshold * .5 + .5 + return ((t + value * quantize) | 0) / quantize +} \ No newline at end of file diff --git a/src/math/rotate-point.js b/src/math/rotate-point.js new file mode 100644 index 0000000..cc62408 --- /dev/null +++ b/src/math/rotate-point.js @@ -0,0 +1,9 @@ + +export default function rotatePoint(c, p, radians) { + const cos = Math.cos(radians) + const sin = Math.sin(radians) + return { + x: (cos * (p.x - c.x)) + (sin * (p.y - c.y)) + c.x, + y: (cos * (p.y - c.y)) - (sin * (p.x - c.x)) + c.y + } +} \ No newline at end of file diff --git a/src/math/to-fraction.js b/src/math/to-fraction.js new file mode 100644 index 0000000..2546392 --- /dev/null +++ b/src/math/to-fraction.js @@ -0,0 +1,16 @@ +// pow: 6 = 1/2^6 = 1/64 +export default function toFraction(val, pow = 6) { + let denom = Math.pow(2, pow) + const sign = val < 0 ? '-' : '' + val = Math.abs(val) + const stp = 1 / denom + const int = Math.floor(val) + let num = Math.round((val - int) / stp) + if (int == val || num == 0) return `${sign}${int}` + while (num > 0 && num % 2 == 0) { + num /= 2 + denom /= 2 + } + if (int != 0) return `${sign}${int} ${num}/${denom}` + else return `${sign}${num}/${denom}` +} diff --git a/src/math/translate-point.js b/src/math/translate-point.js new file mode 100644 index 0000000..4a788df --- /dev/null +++ b/src/math/translate-point.js @@ -0,0 +1,6 @@ +export default function translatePoint(a, b) { + return { + x: a.x + b.x, + y: a.y + b.y + } +} \ No newline at end of file diff --git a/src/math/wrap-angle.js b/src/math/wrap-angle.js new file mode 100644 index 0000000..6058733 --- /dev/null +++ b/src/math/wrap-angle.js @@ -0,0 +1,5 @@ +import { TAU } from "./contants.js" + +export default function wrapAngle(value) { + return (value + TAU) % TAU +} \ No newline at end of file diff --git a/src/model/audio-metrics.js b/src/model/audio-metrics.js new file mode 100644 index 0000000..3194f2b --- /dev/null +++ b/src/model/audio-metrics.js @@ -0,0 +1,25 @@ + + +export default class AudioMetrics { + #frame = new Uint8Array() + #callback + constructor() { + //wrap(this) + } + + get callback() { + return this.#callback + } + + set callback(value) { + this.#callback = value + } + + get frame() { + return this.#frame + } + + set frame(value) { + this.#frame = value + } +} \ No newline at end of file diff --git a/src/model/channel.js b/src/model/channel.js new file mode 100644 index 0000000..c81c673 --- /dev/null +++ b/src/model/channel.js @@ -0,0 +1,97 @@ +import {A, T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import AudioMetrics from "./audio-metrics.js" +import Dynamics from "./dynamics.js" +import Entity from "./entity.js" +import Voice from "./voice.js" + +export default class Channel extends Entity { + static ACTIVE = "active" + static TRIGGER_RELEASE = "trigger-release" + static RELEASE = "release" + static DELETE = "delete" + #voices = A(Voice, []) + #gain = T(Number, 1.) + #activeVoice = T(String, "") + #name = T(String, randomName()) + #state = T(String, Channel.ACTIVE) + #release = T(Number, .1) + #dynamics = T(Dynamics, {}) + #audioMetrics = new AudioMetrics() + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + get state() { + return this.#state + } + + set state(value) { + this.#state = value + } + + get release() { + return this.#release + } + + set release(value) { + this.#release = value + } + + get voices() { + return this.#voices + } + + set voices(value) { + this.#voices = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get activeVoice() { + return this.#activeVoice + } + + set activeVoice(value) { + this.#activeVoice = value + } + + get dynamics() { + return this.#dynamics + } + + set dynamics(value) { + this.#dynamics = value + } + + get audioMetrics() { + return this.#audioMetrics + } + + findActiveVoice() { + return this.findVoice(this.activeVoice) + } + + findVoice(id) { + return this.voices.find(voice => voice.id === id) + } + +} \ No newline at end of file diff --git a/src/model/default-session.js b/src/model/default-session.js new file mode 100644 index 0000000..a49373d --- /dev/null +++ b/src/model/default-session.js @@ -0,0 +1,1394 @@ +export default function defaultSession() { + return { + "path": [], + "dynamics": { + "threshold": 0.349129697812655, + "scale": 0.38496777395045084, + "potential": 0, + "id": "75261d5c-940e-4d85-9761-e66a178c3625" + }, + "views": [ + { + "path": [], + "navigationCollapsed": true, + "name": "Udriduwo Osnoy", + "id": "b4715183-d30f-4764-8770-2eaef64b2733" + }, + { + "path": [ + "7d8151f4-5ed4-4407-a9e2-662630b1b96e" + ], + "navigationCollapsed": false, + "name": "Aju Snauple", + "id": "21b29821-a9ce-4925-943f-598c481dc48e" + }, + { + "path": [ + "0fcb027f-b166-4da3-8e98-d6daa136a163", + "9371e92c-9c17-4c41-ad60-232e06573e43" + ], + "navigationCollapsed": false, + "name": "Austoul Au", + "id": "6249f2a8-6a9e-4525-bddb-cb4c1f6c7965" + }, + { + "path": [ + "be8dc91c-1c3e-42c8-8337-a903177f615f", + "fbdbca22-274a-4c2b-b7ec-0a435d97efd2", + "gain" + ], + "navigationCollapsed": false, + "name": "Uipreiv Eyb", + "id": "c832e68b-62f3-48b2-a258-63a9c5cf59c0" + } + ], + "mode": "storage", + "activeView": 0, + "name": "Demo", + "channels": [ + { + "name": "Earespu Clou", + "state": "active", + "release": 0.1, + "voices": [ + { + "oscillator": { + "length": 0.5, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.0010143577509948987, + "y": 0.4989980061848962, + "e": 1, + "id": "d9f4c031-901f-4a02-bdae-7ac7c108a404" + }, + { + "x": 0.007359855533129567, + "y": 1, + "e": 1, + "id": "2e11e0e7-a104-42f7-b7c5-4989fe20493f" + }, + { + "x": 0.010773426327540525, + "y": 0.05595143636067705, + "e": 1, + "id": "73c39e01-3087-445f-80f9-97117ee63c75" + }, + { + "x": 0.014791458973981264, + "y": 0.9363412857055664, + "e": 1, + "id": "14748514-146f-4e56-8ec8-b4562eb00f02" + }, + { + "x": 0.026395144838690543, + "y": 0.07840315500895176, + "e": 1, + "id": "71b0bad8-c04f-4284-98bf-03a1c0236f1f" + }, + { + "x": 0.03762604377999357, + "y": 0.8514207204182936, + "e": 1, + "id": "fda8e719-5349-4d40-a828-3b5650639417" + }, + { + "x": 0.05139424279680993, + "y": 0.09842809041341129, + "e": 1, + "id": "66168172-ff4c-4305-919e-1b1249ad3c96" + }, + { + "x": 0.08752013044323004, + "y": 0.8994388580322267, + "e": 1, + "id": "b7eaf147-c5a0-4dd3-9c40-c0127b360a34" + }, + { + "x": 0.12376397338390444, + "y": 0.2208547592163084, + "e": 1, + "id": "7e43dd58-3477-4bcd-aef2-99424bc5071f" + }, + { + "x": 0.24738610615034085, + "y": 0.644672711690267, + "e": 1, + "id": "478694f9-b875-4889-9056-806db93169ad" + }, + { + "x": 0.39602545871077854, + "y": 0.5020783742268882, + "e": 1, + "id": "51c74b73-c865-4bbe-900d-b22ebf87010d" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "fd6df856-add6-49cb-bddf-9d4e02d80b8e" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "86158850-12bc-4e53-87bd-e361e6ee63e3" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "6f5c4b38-b769-43cf-a687-565193b4a4dd" + }, + "e": 2.35, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 0.4004503526937189, + "viewPosition": 0, + "id": "5557abc6-6499-4033-8f5f-345af16dcc1b" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": { + "length": 0.017161351139667155, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.1029294331868491, + "y": 0, + "e": 1, + "id": "45e5381c-43d0-49a6-a352-07d6d893e1b3" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "64094b50-cf66-4ba6-989d-566f13a39236" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "f2417c9a-9e97-4077-8be3-d3f97ae8a636" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "013b4e66-9570-4417-acf7-dba97931448b" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "247672d4-add9-4b6b-8f1d-36a4e5977360" + }, + "e": 2.84, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "1c972134-bf6d-4a76-bb28-fb3fa74c1adc" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "84811779-f604-4f02-b060-5be0313ef0b3" + }, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "1833b7cf-7ca0-42d5-91a9-88b7e8838e09" + }, + "name": "Ie Aysweu", + "gain": 0.5, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "7110ada3-c782-4a7e-987c-26fe547205fc" + }, + { + "oscillator": { + "length": 0.25, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.005726814270019531, + "y": 0.499276161193848, + "e": 1, + "id": "a417f8e9-1813-4005-9b2c-4f9bf27f9812" + }, + { + "x": 0.013080808851455128, + "y": 0.9068705240885417, + "e": 1, + "id": "7a0f0b6c-629b-47dd-8fac-754b7c35aed3" + }, + { + "x": 0.019806649949815958, + "y": 0.03876590728759763, + "e": 1, + "id": "6f9af57b-4960-4e64-8da8-e3691fde974a" + }, + { + "x": 0.04198858473036249, + "y": 0.9609591166178384, + "e": 1, + "id": "e4069bc8-ec89-47f6-a9fb-5e18ff2d5366" + }, + { + "x": 0.04583115047879027, + "y": 0.05836359659830733, + "e": 1, + "id": "41246558-63bf-4e47-a114-6943dfd37698" + }, + { + "x": 0.05918449825710925, + "y": 0.9942452112833647, + "e": 1, + "id": "586fbffa-9f23-42ff-843a-cf01b4a3cae3" + }, + { + "x": 0.06579240163167532, + "y": 0.02501010894775375, + "e": 1, + "id": "c6572915-641f-496d-9137-d0dd4ffe88d5" + }, + { + "x": 0.07741599612765926, + "y": 0.9438126881917317, + "e": 1, + "id": "bc82d405-2094-4fc4-805f-37b822aca6ff" + }, + { + "x": 0.09471691979302488, + "y": 0.11187203725179029, + "e": 1, + "id": "f512a954-787f-4040-9ac6-b5aff7f39ada" + }, + { + "x": 0.12103504604763593, + "y": 0.8723354339599607, + "e": 1, + "id": "c310c2c4-9ca3-4f8b-a191-0615bb767c2f" + }, + { + "x": 0.21491305033365848, + "y": 0.14733664194742838, + "e": 1, + "id": "5761c52b-b20e-4c9a-b771-17ba32aa8434" + }, + { + "x": 0.31263404422336194, + "y": 0.7578954696655276, + "e": 1, + "id": "590b5f2a-3707-4fe9-9533-3bed618111db" + }, + { + "x": 0.5011656019422737, + "y": 0.5021295547485354, + "e": 1, + "id": "13199317-ec56-4bb6-be5e-03d649ccfcee" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "d25fd705-1788-47c9-8118-eaa3f0c4cce0" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "082d55d3-dafa-476c-bd43-3b78b0329abf" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "28a638fc-1629-48fc-8822-f13b8c457c4a" + }, + "e": 3, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "90d49fa0-75de-4379-9bab-9ac6d6ccfa52" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": { + "length": 0.008580675569833577, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.21338992648654576, + "y": 0.2439339955647786, + "e": 1, + "id": "5a6f58d0-23ed-43ea-a8ea-0793ec405221" + }, + { + "x": 0.704262309604222, + "y": 0.6567325592041011, + "e": 1, + "id": "68efaeea-4145-4a7e-9a68-3add2636fb29" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "873926b6-6e27-4242-9798-cf0e0ed24a32" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "ad581199-5c9b-42c4-9946-e74393ede8f3" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "f895418f-e509-469b-9e9d-61f1c17ab230" + }, + "e": 3.16, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "bd23305a-d9b3-49b8-abb6-68d1f9f8f646" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "8cc643e4-7b52-4a5d-b1a8-27ad659e5f1c" + }, + "em": null, + "sx": null, + "sy": null, + "gain": { + "length": 2.4, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.000027868482801451933, + "y": 0.005122184753417969, + "e": 1, + "id": "ed83ad0c-8ac7-437f-8193-c85db885f66b" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "e9753378-06f4-4ba5-beb4-4d0ced54a9f7" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "4e9faa99-2f4b-48ae-8aef-0e163ef89511" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "5e7cfde5-0b0d-4c57-b4ae-bd3523b35306" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "18c4c764-fe84-4605-aed8-596e3ec7983c" + }, + "e": 7.76, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "48e57cea-1da4-42aa-8397-b838bc7c48ae" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "75477d50-783e-49b2-872e-df24d736eb72" + }, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "24436af1-32a8-4bb5-8c66-272d929f641f" + }, + "name": "Oikneu Blespo", + "gain": 0.5, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "8af95214-7ece-4fee-9c9d-60dddf38b713" + } + ], + "gain": 1, + "activeVoice": "", + "dynamics": { + "threshold": 0.2187051292650003, + "scale": 0.3621376901024899, + "potential": 0.472186841488431, + "id": "93491cbf-b0cc-4aa7-8721-9a8854d29b8a" + }, + "id": "7d8151f4-5ed4-4407-a9e2-662630b1b96e" + }, + { + "name": "Eubre Ee", + "state": "active", + "release": 0.1, + "voices": [ + { + "oscillator": { + "length": 0.01362097342615165, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0, + "y": 0, + "e": 1, + "id": "a148103e-0496-4558-a2ce-9641c2009101" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "c5927923-6243-44d9-b781-7186fa347458" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "3238ab8d-3c7b-43f4-bd9c-efd0f2f1389d" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "425f8c7e-9179-4375-b7c7-de744adf3d4d" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "d6b738f5-6fc3-4b51-bc1a-5fb2638bcd75" + }, + "e": 2.39, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "fa5fb2b7-a8f2-485e-abb6-b78fd3ab3b37" + }, + "fm": { + "length": 9.6, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.125, + "y": 0.5, + "e": 1, + "id": "547eff7b-5e1c-4128-8ac3-aa474966a430" + }, + { + "x": 0.25, + "y": 0.625, + "e": 1, + "id": "f447ad3d-1a59-4271-b8f5-e32d6bdb4597" + }, + { + "x": 0.375, + "y": 0.5, + "e": 1, + "id": "471c5dc7-f679-4aee-92da-ea2c54f52140" + }, + { + "x": 0.5, + "y": 0.4166666666666667, + "e": 1, + "id": "4e69082e-c2bd-4bf1-af49-4ffa1a812e84" + }, + { + "x": 0.625, + "y": 0.5, + "e": 1, + "id": "177dcfff-5778-439b-9dce-ca74da8c9277" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "14fa6206-cb46-4aef-9f1b-7a7346e3c000" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "df1468d1-a05d-451d-96cd-240b5fac6993" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "5356d2f3-0967-42a4-8c7a-494fc224a0b9" + }, + "e": 1000, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 8, + "gridXThreshold": 0, + "gridY": 24, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "ff360c51-4447-43eb-8b6a-1a08a67d67a8" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "392f55d2-b2fe-4823-811a-d68ca0e50666" + }, + "fmRange": 2, + "transpose": null, + "am": null, + "em": { + "length": 9.6, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.125, + "y": 0.33648459116617835, + "e": 1, + "id": "4f3ba4a2-3bcc-441f-8f4d-62e436b52352" + }, + { + "x": 0.375, + "y": 0.9756914774576826, + "e": 1, + "id": "7e48bb99-bd8a-43ce-9bdb-bc7f2e4db60e" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "7d76b48e-5613-4539-8eec-b5311e2f7d73" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "60aee2da-ef52-4baa-8a03-3a54c2535f8c" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "c29f4763-9ef6-4834-805d-3a5a18b69e11" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 8, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "67f8dc20-d2ea-4502-820d-88141c4f3d09" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "19801666-cd16-42c3-b7a1-c1d31f667ec3" + }, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "b432c48a-f2d3-4d6e-a37d-15036eb17ce0" + }, + "name": "Ui Oashee", + "gain": 0.5, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "9371e92c-9c17-4c41-ad60-232e06573e43" + } + ], + "gain": 0.8722687054057093, + "activeVoice": "", + "dynamics": { + "threshold": 0.30829745376588447, + "scale": 0.4931716396287149, + "potential": 0.3933952664454105, + "id": "f2df0cad-6d71-474e-abec-7dec0d312aed" + }, + "id": "0fcb027f-b166-4da3-8e98-d6daa136a163" + }, + { + "name": "Ee Stray", + "state": "active", + "release": 0.1, + "voices": [ + { + "oscillator": { + "length": 0.0021451688924583943, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0, + "y": 0, + "e": 1, + "id": "04e39018-92c8-43ab-b590-122472038296" + }, + { + "x": 0.5159289395595947, + "y": 1, + "e": 1, + "id": "ad0a6e8d-878c-42fd-a516-fc932f6279b8" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "decfb419-8b60-403e-b475-2adc7577744b" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "b8666d08-4216-4a5b-8544-8854efe32ac9" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "10724937-b219-4d6c-81d4-7b47fdc67d1a" + }, + "e": 4.8100000000000005, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "4addc060-4afd-4be8-b9a8-85f5333311ca" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": { + "length": 2.4, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.3125, + "y": 0, + "e": 1, + "id": "2f6a68fc-f2a5-473c-be0f-0a95df3f68ec" + }, + { + "x": 0.5, + "y": 0.8668719927469877, + "e": 1, + "id": "d070ab04-209c-4897-b47d-a3ff95479062" + }, + { + "x": 1, + "y": 0.006402969360351563, + "e": 1, + "id": "4a30e08f-2ccf-413a-b6b9-d93b93e63438" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "5c79efcc-c048-405b-944b-edae6a5d4101" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "e032aa21-82d1-43fe-9052-f7dfa7b717e0" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "925b1a95-478d-4402-b994-373f2c3a73f2" + }, + "e": 3.08, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 16, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "74f79471-ae1a-402d-b72c-8a8576feef3f" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "ed597a7b-a06e-468d-9a7e-19e68aa56224" + }, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "47d1e8ee-8ad7-4f98-ba72-2c4f9b22aafe" + }, + "name": "Ezu Cleysle", + "gain": 0.12437363679347828, + "state": "sustain", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "fbdbca22-274a-4c2b-b7ec-0a435d97efd2" + } + ], + "gain": 0.1845072824868422, + "activeVoice": "", + "dynamics": { + "threshold": 0.4938849770556756, + "scale": 0.3831000405849414, + "potential": 0, + "id": "daa5abc9-a8d1-4083-ae5d-d4671c5215fe" + }, + "id": "be8dc91c-1c3e-42c8-8337-a903177f615f" + } + ], + "channelMix": { + "x": 0.03666469029017857, + "y": 0.030744280133928572, + "id": "5a92a719-197c-4c20-83af-c14e2e47d45b" + }, + "main": 0.5071588313070478, + "potential": 0.33, + "mute": false, + "activeChannel": "", + "solo": "", + "keyboardSettings": { + "keys": 24, + "start": 0.00909090909090909, + "increment": 1, + "subdivisions": 12, + "startDriver": "note", + "id": "967b0c80-66c8-40fa-8864-5f87f342d3d2" + }, + "showKeyboardSettings": true, + "settings": { + "tempo": 0.4166666666666667, + "tempoDriver": "bpm", + "id": "d6441151-393b-4e5d-9927-1381521615c1" + }, + "defaults": { + "voice": { + "oscillator": { + "length": 0.00909090909090909, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0, + "y": 0, + "e": 1, + "id": "97666f93-2662-4e1b-98ac-ac4666f42ee9" + }, + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "0aeac999-1782-4724-96eb-b1cc52ed6b3b" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "03f442e2-0199-43a4-b919-b8967ab64b01" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "f27e6f85-39bb-483f-ba6d-00c30fbd2925" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "1ebdffa1-71bd-465b-a6c9-007461d034ef" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "82345695-05f5-413e-ad73-739fee387e0c" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "bdf99b30-d15f-4b70-be10-3c5410c2bbf6" + }, + "name": "Eysquooz", + "gain": 0.5, + "state": "idle", + "on": 0, + "off": 9007199254740991, + "attack": 1, + "release": 1, + "path": [], + "bus": "main", + "id": "03aa2d3f-25af-481f-add0-e7db23dfb03a" + }, + "am": { + "length": 0.00909090909090909, + "tempoSync": false, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "96d39558-fcd6-447f-b2dc-316b167dfb33" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "715967ca-46e4-457d-a52a-99121688c936" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "430e4279-4f9e-4893-b9b1-15984b3ecc83" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "4b0eb2dc-fb36-46f4-a9a6-e499d0d5c500" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "5b540d28-1f14-4e31-9440-668256629f54" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "note", + "id": "ba07b507-b56e-4e99-8ee9-42c38d7e6e6d" + }, + "fm": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 0.5, + "e": 1, + "id": "0e4988c9-b7fa-476e-b2ef-1b9316a18fe4" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "383fa204-c078-4766-aa39-50cb0e501657" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "73cac1dc-3b85-4f7e-bc0c-25237a2e0d2b" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "09c90b7a-c840-4faf-b404-50b6ce45f92f" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "bb68cafd-6400-4581-aa7f-ea4ad13dcbb8" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "bar", + "id": "695e06be-163e-43e5-8ff2-fa015496935e" + }, + "gain": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "8bf671f3-5911-4d00-9c60-04ce410b5e55" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "ca3176b1-d13c-4449-bdcb-ace966fb0137" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "fb4444e3-9024-4bb0-9a0d-9f1221c6518d" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "c9257aae-ea03-4a9c-82d0-d5aba8f7f60f" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "9e5fc09d-f5d0-44aa-abbc-db8e86024fe6" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "b74eff92-2818-431e-b4da-2b3f44bf8d5a" + }, + "em": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "ddccc59b-c5f9-4c99-8034-aaffe92890b0" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "5dc449fa-1a01-43fe-a8a1-d3660ed93fd6" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "c5bd02a5-e732-4414-befc-2b84fba41319" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "d7d81706-696f-468b-a08d-c2f18a2f7d48" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "d3826b07-1a60-447b-a729-5ae679516b5e" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "ccf28988-1159-465d-81c5-294686266f34" + }, + "sx": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 1, + "e": 1, + "id": "d9d9adda-4f6e-4ea1-9f05-daf44bf0af5b" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "9397d5d5-3347-4272-bbf5-2615b36bbe6d" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "f4997359-7cda-4387-9f41-f8788b0c3cdd" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "81cd5804-8fef-4509-bbd2-93f302d36674" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "99d91df9-5718-451a-94aa-d18be9d02346" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "3fa6d0bd-f9c8-44b5-a510-f9872abef406" + }, + "transpose": { + "length": 2.559999999999999, + "tempoSync": true, + "wave": { + "points": [ + { + "x": 0.5, + "y": 0.5, + "e": 1, + "id": "29161cd9-b6dc-4c24-8d59-5faefcd82262" + } + ], + "transformCenter": { + "x": 0.5, + "y": 0.5, + "id": "8ba68d9f-cd3d-47e0-81b3-82516fc2f971" + }, + "transformScale": { + "x": 1, + "y": 1, + "id": "2e05de32-4ab7-4286-9f39-4d97f56fb920" + }, + "transformRange": { + "x": 1, + "y": 1, + "id": "80e796f3-e869-4738-b7dc-a0f5205d39bf" + }, + "e": 1, + "quantizeX": 9007199254740991, + "quantizeXThreshold": -1, + "quantizeY": 9007199254740991, + "quantizeYThreshold": 0, + "gridX": 9007199254740991, + "gridXThreshold": 0, + "gridY": 9007199254740991, + "gridYThreshold": 0, + "viewZoom": 1, + "viewPosition": 0, + "id": "7da16428-5338-4003-ba12-5e2e4b227ec7" + }, + "fm": null, + "fmRange": 2, + "transpose": null, + "am": null, + "em": null, + "sx": null, + "sy": null, + "gain": null, + "phase": 0, + "phaseShift": 0, + "lengthDriver": "fraction", + "id": "3e35417f-f955-4293-8120-b0fe26e801bb" + }, + "id": "6e0880eb-80d6-4814-851e-6aee063a0a44" + }, + "navigationMode": "siblings", + "created": 1708897287648, + "state": "playing", + "keyboardFocus": [ + "be8dc91c-1c3e-42c8-8337-a903177f615f", + "fbdbca22-274a-4c2b-b7ec-0a435d97efd2", + "gain" + ], + "id": "41f3622c-416e-471e-bd34-6205755f00b5", + "tree": { + "type": "session", + "branches": [ + { + "type": "channel", + "branches": [ + { + "type": "voice", + "branches": [ + { + "type": "am", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 1, + "depth": 2 + }, + { + "type": "voice", + "branches": [ + { + "type": "am", + "branches": [], + "span": 1, + "depth": 1 + }, + { + "type": "gain", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 2, + "depth": 2 + } + ], + "span": 3, + "depth": 3 + }, + { + "type": "channel", + "branches": [ + { + "type": "voice", + "branches": [ + { + "type": "fm", + "branches": [], + "span": 1, + "depth": 1 + }, + { + "type": "em", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 2, + "depth": 2 + } + ], + "span": 2, + "depth": 3 + }, + { + "type": "channel", + "branches": [ + { + "type": "voice", + "branches": [ + { + "type": "gain", + "branches": [], + "span": 1, + "depth": 1 + } + ], + "span": 1, + "depth": 2 + } + ], + "span": 1, + "depth": 3 + } + ], + "span": 6, + "depth": 4 + }, + "changed": 1708902557380 + } + +} \ No newline at end of file diff --git a/src/model/defaults.js b/src/model/defaults.js new file mode 100644 index 0000000..468caf1 --- /dev/null +++ b/src/model/defaults.js @@ -0,0 +1,83 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" +import Voice from "./voice.js" +import WaveSplineOscillator from "./wave-spline-oscillator.js" + +export default class Defaults extends Entity { + + #voice = T(Voice, { + gain: 0.5, + oscillator: {length: 1/110, lengthDriver: "note", wave:{points:[{x:0, y:0}, {x:.5, y:1}]}} + }) + #am = T(WaveSplineOscillator, {length: 1/110, lengthDriver: "note", wave:{points:[{x:.5, y:1}]}}) + #fm = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "bar", wave:{points:[{x:.5, y:.5}]}}) + #gain = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:1}]}}) + #em = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:1}]}}) + #sx = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:1}]}}) + #transpose = T(WaveSplineOscillator, {length: 2, tempoSync: true, lengthDriver: "fraction", wave:{points:[{x:.5, y:.5}]}}) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get voice() { + return this.#voice + } + + set voice(value) { + this.#voice = value + } + + get am() { + return this.#am + } + + set am(value) { + this.#am = value + } + + get fm() { + return this.#fm + } + + set fm(value) { + this.#fm = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get em() { + return this.#em + } + + set em(value) { + this.#em = value + } + + get sx() { + return this.#sx + } + + set sx(value) { + this.#sx = value + } + + get transpose() { + return this.#transpose + } + + set transpose(value) { + this.#transpose = value + } + + +} \ No newline at end of file diff --git a/src/model/dynamics.js b/src/model/dynamics.js new file mode 100644 index 0000000..329e6cc --- /dev/null +++ b/src/model/dynamics.js @@ -0,0 +1,40 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class Dynamics extends Entity { + + #threshold = T(Number, .5) + #scale = T(Number, 1) + #potential = T(Number, 0) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get threshold() { + return this.#threshold + } + + set threshold(value) { + this.#threshold = value + } + + get scale() { + return this.#scale + } + + set scale(value) { + this.#scale = value + } + + get potential() { + return this.#potential + } + + set potential(value) { + this.#potential = value + } +} \ No newline at end of file diff --git a/src/model/entity.js b/src/model/entity.js new file mode 100644 index 0000000..5342225 --- /dev/null +++ b/src/model/entity.js @@ -0,0 +1,17 @@ +import generateId from "../data/generate-id.js" +import {T} from "../glue/t.js" + +export default class Entity { + #id = T(String, generateId()) + constructor(data = {}) { + Object.assign(this, data) + } + + get id() { + return this.#id + } + + set id(value) { + this.#id = value + } +} \ No newline at end of file diff --git a/src/model/generate-tree.js b/src/model/generate-tree.js new file mode 100644 index 0000000..825880b --- /dev/null +++ b/src/model/generate-tree.js @@ -0,0 +1,37 @@ +export default function generateTree(session) { + let h = 0 + let W = 0 + const sessionBranch = {type: "session", branches: [], span: 0, depth: 1} + session.channels.forEach(channel => { + const channelBranch = {type: "channel", branches: [], span: 0, depth: 1} + sessionBranch.branches.push(channelBranch) + channel.voices.forEach(voice => { + const voiceBranch = generateRecursiveOscillatorTree("voice", voice.oscillator) + channelBranch.branches.push(voiceBranch) + channelBranch.span += voiceBranch.span + channelBranch.depth = Math.max(channelBranch.depth, voiceBranch.depth + 1) + }) + channelBranch.span = Math.max(1, channelBranch.span) + sessionBranch.span += channelBranch.span + sessionBranch.depth = Math.max(sessionBranch.depth, channelBranch.depth + 1) + }) + sessionBranch.span = Math.max(1, sessionBranch.span) + return sessionBranch +} + +function generateRecursiveOscillatorTree(type, oscillator) { + const oscillatorBranch = {type, branches:[], span: 0, depth: 1} + if (oscillator.am) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("am", oscillator.am)) + if (oscillator.fm) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("fm", oscillator.fm)) + if (oscillator.transpose) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("transpose", oscillator.transpose)) + if (oscillator.em) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("em", oscillator.em)) + if (oscillator.sx) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("sx", oscillator.sx)) + if (oscillator.gain) oscillatorBranch.branches.push(generateRecursiveOscillatorTree("gain", oscillator.gain)) + oscillatorBranch.branches.forEach((branch)=>{ + oscillatorBranch.span += branch.span + oscillatorBranch.depth = Math.max(oscillatorBranch.depth, branch.depth +1) + }) + oscillatorBranch.span = Math.max(1, oscillatorBranch.span) + + return oscillatorBranch +} \ No newline at end of file diff --git a/src/model/keyboard-settings.js b/src/model/keyboard-settings.js new file mode 100644 index 0000000..438fd92 --- /dev/null +++ b/src/model/keyboard-settings.js @@ -0,0 +1,60 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class KeyboardSettings extends Entity { + + #keys = T(Number, 24) + #start = T(Number, 1/110) + #increment = T(Number, 1) + #subdivisions = T(Number, 12) + #startDriver = T(String, "note") + + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get keys() { + return this.#keys + } + + set keys(value) { + this.#keys = value + } + + get start() { + return this.#start + } + + set start(value) { + this.#start = value + } + + get increment() { + return this.#increment + } + + set increment(value) { + this.#increment = value + } + + get subdivisions() { + return this.#subdivisions + } + + set subdivisions(value) { + this.#subdivisions = value + } + + get startDriver() { + return this.#startDriver + } + + set startDriver(value) { + this.#startDriver = value + } + +} \ No newline at end of file diff --git a/src/model/point.js b/src/model/point.js new file mode 100644 index 0000000..ad74db9 --- /dev/null +++ b/src/model/point.js @@ -0,0 +1,29 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class Point extends Entity { + #x = T(Number, 0) + #y = T(Number, 0) + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get x() { + return this.#x + } + + set x(value) { + this.#x = value + } + + get y() { + return this.#y + } + + set y(value) { + this.#y = value + } +} \ No newline at end of file diff --git a/src/model/reset-channel.js b/src/model/reset-channel.js new file mode 100644 index 0000000..debf643 --- /dev/null +++ b/src/model/reset-channel.js @@ -0,0 +1,9 @@ +import Channel from "./channel.js" +import resetVoice from "./reset-voice.js" + +export default function resetChannel(channel) { + channel.state = Channel.ACTIVE + channel.voices.forEach(voice=>{ + resetVoice(voice) + }) +} \ No newline at end of file diff --git a/src/model/reset-state.js b/src/model/reset-state.js new file mode 100644 index 0000000..4873fc2 --- /dev/null +++ b/src/model/reset-state.js @@ -0,0 +1,12 @@ +import Channel from "./channel.js"; +import resetChannel from "./reset-channel.js"; +import Session from "./session.js"; +import Voice from "./voice.js"; + +export default function resetState(session) { + if (!session) return + session.state = Session.TRIGGER_PLAY + session.channels.forEach(channel => { + resetChannel(channel) + }); +} \ No newline at end of file diff --git a/src/model/reset-voice.js b/src/model/reset-voice.js new file mode 100644 index 0000000..4613a4e --- /dev/null +++ b/src/model/reset-voice.js @@ -0,0 +1,13 @@ +import Voice from "./voice.js" + +export default function resetVoice(voice) { + if ( + voice.state === Voice.ATTACK + || voice.state === Voice.SUSTAIN + + ) { + voice.state = Voice.TRIGGER_ATTACK + } else if (voice.state === Voice.TRIGGER_RELEASE || voice.state === Voice.RELEASE) { + voice.state = Voice.IDLE + } +} \ No newline at end of file diff --git a/src/model/session.js b/src/model/session.js new file mode 100644 index 0000000..9fc3154 --- /dev/null +++ b/src/model/session.js @@ -0,0 +1,355 @@ +import {A, T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import AudioMetrics from "./audio-metrics.js" +import Channel from "./channel.js" +import Defaults from "./defaults.js" +import Dynamics from "./dynamics.js" +import Entity from "./entity.js" +import KeyboardSettings from "./keyboard-settings.js" +import Point from "./point.js" +import Settings from "./settings.js" +import View from "./view.js" + +const SYNCED_VIEWS = ["bar", "fraction"] + +export default class Session extends Entity { + + static TRIGGER_PAUSE = "trigger-pause" + static TRIGGER_PLAY = "trigger-play" + static PLAY = "play" + static PAUSE = "pause" + static PLAYING = "playing" + static PAUSED = "paused" + + static SIBLINGS = "siblings" + static MULTILINE = "multiline" + static COMPACT = "compact" + + #created = T(Number, Date.now()) + #settings = T(Settings, {}) + #channels = A(Channel, []) + #main = T(Number, 1.) + #mute = T(Boolean, false) + #activeChannel = T(String,"") + #keyboardSettings = T(KeyboardSettings, {}) + #channelMix = T(Point, {x:0, y:0}) + #defaults = T(Defaults, {}) + #dynamics = T(Dynamics, {}) + + #potential = T(Number, 0.33) + + #name = T(String, randomName()) + #path = A(String, []) + #keyboardFocus = A(String, []) + + #navigationMode = T(String, Session.SIBLINGS) + + #views = A(View, [{}]) + #activeView = T(Number, 0) + #mode = T(String, "view") + #showKeyboardSettings = T(Boolean, true) + + #tempoReference = -1 + #audioMetrics = new AudioMetrics() + #solo = T(String,"") + #state = T(String, Session.PLAYING) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get path() { + return this.#path + } + + set path(value) { + this.#path = value + } + + get dynamics() { + return this.#dynamics + } + + set dynamics(value) { + this.#dynamics = value + } + + get views() { + return this.#views + } + + set views(value) { + this.#views = value + } + + get mode() { + return this.#mode + } + + set mode(value) { + this.#mode = value + } + + get activeView() { + return this.#activeView + } + + set activeView(value) { + this.#activeView = value + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + get channels() { + return this.#channels + } + + set channels(value) { + this.#channels = value + } + + get channelMix() { + return this.#channelMix + } + + set channelMix(value) { + this.#channelMix = value + } + + get main() { + return this.#main + } + + set main(value) { + this.#main = value + } + + get potential() { + return this.#potential + } + + set potential(value) { + this.#potential = value + } + + get mute() { + return this.#mute + } + + set mute(value) { + this.#mute = value + } + + get activeChannel() { + return this.#activeChannel + } + + set activeChannel(value) { + this.#activeChannel = value + } + + get solo() { + return this.#solo + } + + set solo(value) { + this.#solo = value + } + + get keyboardSettings() { + return this.#keyboardSettings + } + + set keyboardSettings(value) { + this.#keyboardSettings = value + } + + get showKeyboardSettings() { + return this.#showKeyboardSettings + } + + set showKeyboardSettings(value) { + this.#showKeyboardSettings = value + } + + get settings() { + return this.#settings + } + + set settings(value) { + this.#settings = value + } + + get defaults() { + return this.#defaults + } + + set defaults(value) { + this.#defaults = value + } + + get navigationMode() { + return this.#navigationMode + } + + set navigationMode(value) { + this.#navigationMode = value + } + + get created() { + return this.#created + } + + set created(value) { + this.#created = value + } + + get state() { + return this.#state + } + + set state(value) { + this.#state = value + } + + get audioMetrics() { + return this.#audioMetrics + } + + get keyboardFocus() { + return this.#keyboardFocus + } + + set keyboardFocus(value) { + this.#keyboardFocus = value + } + + getPathReference(path) { + let ref = this + + for(let i=0; i{ + view.path = this.getValidSubpath(view.path) + }) + } + + findActiveChannel() { + return this.findChannel(this.activeChannel) + } + + findChannel(id) { + return this.channels.find(channel => channel.id === id) + } + + voiceSolo(id) { + if (this.solo === id) { + this.solo = "" + } else { + this.solo = id + } + this.channels.forEach(channel => { + channel.voices.forEach(voice => { + if(voice.id === this.solo) { + voice.bus = "solo" + } else { + voice.bus = "main" + } + }) + }) + } + + zeroAll() { + const zeroRecursive = (osc) => { + osc.phase = 0 + if (osc.fm) zeroRecursive(osc.fm) + if (osc.transpose) zeroRecursive(osc.transpose) + if (osc.am) zeroRecursive(osc.am) + if (osc.em) zeroRecursive(osc.em) + if (osc.sx) zeroRecursive(osc.sx) + if (osc.sy) zeroRecursive(osc.sy) + if (osc.gain) zeroRecursive(osc.gain) + } + this.channels.forEach(channel => { + channel.voices.forEach(voice => { + zeroRecursive(voice.oscillator) + }) + }) + } + + syncTempo() { + const multiplyRecursive = (osc, factor) => { + if (osc.tempoSync) osc.length *= factor + if (osc.fm) multiplyRecursive(osc.fm, factor) + if (osc.fm) multiplyRecursive(osc.transpose, factor) + if (osc.am) multiplyRecursive(osc.am, factor) + if (osc.em) multiplyRecursive(osc.em, factor) + if (osc.sx) multiplyRecursive(osc.sx, factor) + if (osc.sy) multiplyRecursive(osc.sy, factor) + if (osc.gain) multiplyRecursive(osc.gain, factor) + } + if (this.#tempoReference != -1) { + const factor = this.#tempoReference / this.settings.tempo + this.channels.forEach(channel => { + channel.voices.forEach(voice => { + multiplyRecursive(voice.oscillator, factor) + }) + }) + multiplyRecursive(this.defaults.voice.oscillator, factor) + multiplyRecursive(this.defaults.am, factor) + multiplyRecursive(this.defaults.fm, factor) + multiplyRecursive(this.defaults.transpose, factor) + multiplyRecursive(this.defaults.gain, factor) + multiplyRecursive(this.defaults.em, factor) + multiplyRecursive(this.defaults.sx, factor) + } + + this.#tempoReference = this.settings.tempo + } + +} \ No newline at end of file diff --git a/src/model/settings.js b/src/model/settings.js new file mode 100644 index 0000000..9bb749f --- /dev/null +++ b/src/model/settings.js @@ -0,0 +1,32 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class Settings extends Entity { + + #tempo = T(Number, 120 / 60 / 4) // time per beat + #tempoDriver = T(String, "bpm") + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get tempo() { + return this.#tempo + } + + set tempo(value) { + this.#tempo = value + } + + get tempoDriver() { + return this.#tempoDriver + } + + set tempoDriver(value) { + this.#tempoDriver = value + } + +} \ No newline at end of file diff --git a/src/model/view.js b/src/model/view.js new file mode 100644 index 0000000..32bf188 --- /dev/null +++ b/src/model/view.js @@ -0,0 +1,43 @@ +import {T, O, A} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import Entity from "./entity.js" + +export default class View extends Entity { + + #name = T(String, randomName()) + #path = A(String, []) + #navigationCollapsed = false + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get path() { + return this.#path + } + + set path(value) { + this.#path = value + } + + get navigationCollapsed() { + return this.#navigationCollapsed + } + + set navigationCollapsed(value) { + this.#navigationCollapsed = value + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + +} \ No newline at end of file diff --git a/src/model/voice.js b/src/model/voice.js new file mode 100644 index 0000000..0775070 --- /dev/null +++ b/src/model/voice.js @@ -0,0 +1,120 @@ +import {A, T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import randomName from "../utils/random-name.js" +import Entity from "./entity.js" +import WaveSplineOscillator from "./wave-spline-oscillator.js" + +export default class Voice extends Entity { + static IDLE = "idle" + static TRIGGER_ATTACK = "trigger-attack" + static ATTACK = "attack" + static SUSTAIN = "sustain" + static TRIGGER_RELEASE = "trigger-release" + static RELEASE = "release" + static TRIGGER_DELETE = "trigger-delete" + static DELETE_RELEASE = "delete-release" + static DELETE = "delete" + + #oscillator = T(WaveSplineOscillator, {}) + + #on = T(Number, 0) + #off = T(Number, Number.MAX_SAFE_INTEGER) + + #gain = T(Number, 1) + + #attack = T(Number, 1) + #release = T(Number, 1) + #path = A(String, []) + + #name = T(String, randomName()) + + #bus = T(String, "main") + + #state = T(String, Voice.IDLE) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get oscillator() { + return this.#oscillator + } + + set oscillator(value) { + this.#oscillator = value + } + + get name() { + return this.#name + } + + set name(value) { + this.#name = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get state() { + return this.#state + } + + set state(value) { + this.#state = value + } + + get on() { + return this.#on + } + + set on(value) { + this.#on = value + } + + get off() { + return this.#off + } + + set off(value) { + this.#off = value + } + + get attack() { + return this.#attack + } + + set attack(value) { + this.#attack = value + } + + get release() { + return this.#release + } + + set release(value) { + this.#release = value + } + + get path() { + return this.#path + } + + set path(value) { + this.#path = value + } + + get bus() { + return this.#bus + } + + set bus(value) { + this.#bus = value + } +} \ No newline at end of file diff --git a/src/model/wave-spline-oscillator.js b/src/model/wave-spline-oscillator.js new file mode 100644 index 0000000..2cdc65b --- /dev/null +++ b/src/model/wave-spline-oscillator.js @@ -0,0 +1,140 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" +import WaveSpline from "./wave-spline.js" + +export default class WaveSplineOscillator extends Entity { + #length = T(Number, 1) + #lengthDriver = T(String, "frequency") + #tempoSync = T(Boolean, false) + #wave = T(WaveSpline, {}) + #phase = T(Number,0) + #phaseShift = T(Number, 0) + #fm = T(WaveSplineOscillator) + #fmRange = T(Number, 2) + #am = T(WaveSplineOscillator) + #em = T(WaveSplineOscillator) + #sx = T(WaveSplineOscillator) + #sy = T(WaveSplineOscillator) + #gain = T(WaveSplineOscillator) + #transpose = T(WaveSplineOscillator) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get length() { + return this.#length + } + + set length(value) { + this.#length = value + } + + get tempoSync() { + return this.#tempoSync + } + + set tempoSync(value) { + this.#tempoSync = value + } + + get wave() { + return this.#wave + } + + set wave(value) { + this.#wave = value + } + + get fm() { + return this.#fm + } + + set fm(value) { + this.#fm = value + } + + get fmRange() { + return this.#fmRange + } + + set fmRange(value) { + this.#fmRange = value + } + + get transpose() { + return this.#transpose + } + + set transpose(value) { + this.#transpose = value + } + + get am() { + return this.#am + } + + set am(value) { + this.#am = value + } + + get em() { + return this.#em + } + + set em(value) { + this.#em = value + } + + get sx() { + return this.#sx + } + + set sx(value) { + this.#sx = value + } + + get sy() { + return this.#sy + } + + set sy(value) { + this.#sy = value + } + + get gain() { + return this.#gain + } + + set gain(value) { + this.#gain = value + } + + get phase() { + return this.#phase + } + + set phase(value) { + this.#phase = value + } + + get phaseShift() { + return this.#phaseShift + } + + set phaseShift(value) { + this.#phaseShift = value + } + + get lengthDriver() { + return this.#lengthDriver + } + + set lengthDriver(value) { + this.#lengthDriver = value + } + +} \ No newline at end of file diff --git a/src/model/wave-spline-point.js b/src/model/wave-spline-point.js new file mode 100644 index 0000000..a39bae4 --- /dev/null +++ b/src/model/wave-spline-point.js @@ -0,0 +1,38 @@ +import {T} from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" + +export default class WaveSplinePoint extends Entity { + #x = T(Number, 0) + #y = T(Number, 0) + #e = T(Number, 1) + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get x() { + return this.#x + } + + set x(value) { + this.#x = value + } + + get y() { + return this.#y + } + + set y(value) { + this.#y = value + } + + get e() { + return this.#e + } + + set e(value) { + this.#e = value + } +} \ No newline at end of file diff --git a/src/model/wave-spline.js b/src/model/wave-spline.js new file mode 100644 index 0000000..c309288 --- /dev/null +++ b/src/model/wave-spline.js @@ -0,0 +1,168 @@ +import { T, A } from "../glue/t.js" +import wrap from "../glue/wrap.js" +import Entity from "./entity.js" +import Point from "./point.js" +import WaveSplinePoint from "./wave-spline-point.js" + +export default class WaveSpline extends Entity { + #e = T(Number, 1) + #points = A(WaveSplinePoint) + #quantizeX = T(Number, Number.MAX_SAFE_INTEGER) + #quantizeXThreshold = T(Number, -1) + #quantizeY = T(Number, Number.MAX_SAFE_INTEGER) + #quantizeYThreshold = T(Number, 0) + #gridX = T(Number, Number.MAX_SAFE_INTEGER) + #gridXThreshold = T(Number, 0) + #gridY = T(Number, Number.MAX_SAFE_INTEGER) + #gridYThreshold = T(Number, 0) + + #viewZoom = T(Number, 1) + #viewPosition = T(Number, 0) + + #transformCenter = T(Point, {x: 0.5, y: 0.5}) + #transformScale = T(Point, {x: 1, y: 1}) + #transformRange = T(Point, {x: 1.0, y: 1.0}) + + constructor(data = {}) { + super() + wrap(this) + Object.assign(this, data) + } + + get points() { + return this.#points + } + + set points(value) { + this.#points = value + } + + + get transformCenter() { + return this.#transformCenter + } + + set transformCenter(value) { + this.#transformCenter = value + } + + get transformScale() { + return this.#transformScale + } + + set transformScale(value) { + this.#transformScale = value + } + + get transformRange() { + return this.#transformRange + } + + set transformRange(value) { + this.#transformRange = value + } + + get e() { + return this.#e + } + + set e(value) { + this.#e = value + } + + get quantizeX() { + return this.#quantizeX + } + + set quantizeX(value) { + this.#quantizeX = value + } + + get quantizeXThreshold() { + return this.#quantizeXThreshold + } + + set quantizeXThreshold(value) { + this.#quantizeXThreshold = value + } + + get quantizeY() { + return this.#quantizeY + } + + set quantizeY(value) { + this.#quantizeY = value + } + + get quantizeYThreshold() { + return this.#quantizeYThreshold + } + + set quantizeYThreshold(value) { + this.#quantizeYThreshold = value + } + + get gridX() { + return this.#gridX + } + + set gridX(value) { + this.#gridX = value + } + + get gridXThreshold() { + return this.#gridXThreshold + } + + set gridXThreshold(value) { + this.#gridXThreshold = value + } + + get gridY() { + return this.#gridY + } + + set gridY(value) { + this.#gridY = value + } + + get gridYThreshold() { + return this.#gridYThreshold + } + + set gridYThreshold(value) { + this.#gridYThreshold = value + } + + get viewZoom() { + return this.#viewZoom + } + + set viewZoom(value) { + this.#viewZoom = value + } + + get viewPosition() { + return this.#viewPosition + } + + set viewPosition(value) { + this.#viewPosition = value + } + + insertPoint(value) { + this.points.push(value) + this.sort() + } + + removePoint(value) { + this.points.splice(this.#points.indexOf(value), 1) + } + + sort() { + this.points.sort((a, b)=>{ + if (a.x === b.x) return (a.id < b.id) ? -1 : 1 + return (a.x < b.x) ? -1 : 1 + }) + } +} \ No newline at end of file diff --git a/src/music/beautify-frequency.js b/src/music/beautify-frequency.js new file mode 100644 index 0000000..1cbd4c3 --- /dev/null +++ b/src/music/beautify-frequency.js @@ -0,0 +1,27 @@ +export default function beautifyFrequency(frequency) { + /* + 1 Hz + 1.34 Hz + 100.31 Hz + 440 Hz + 1.3 kHz + 100.3 kHz + */ + let maxDigits = 4 + let value = frequency + let unit = "Hz" + if (value > 1e3) { + value /= 1e3 + unit = "kHz" + } + let fractionDigits = 1 + for (let e = 0; e < 3; e++) { + if (value <= Math.pow(10, e)) { + fractionDigits = maxDigits - e + break; + } + } + const scale = Math.pow(10, fractionDigits) + value = Math.round(value * scale) / scale + return { value, unit } +} \ No newline at end of file diff --git a/src/music/beautify-time.js b/src/music/beautify-time.js new file mode 100644 index 0000000..cac896c --- /dev/null +++ b/src/music/beautify-time.js @@ -0,0 +1,26 @@ +export default function beautifyTime(seconds) { + let maxDigits = 3 + let value = seconds + let unit = "s" + + if (value < 1) { + value *= 1000 + unit = "ms" + } else if (value >= 60) { + value /= 60 + unit = "m" + } else if (value >= 60*60) { + value /= 60*60 + unit = "h" + } + let fractionDigits = 1 + for (let e = 0; e < 3; e++) { + if (value <= Math.pow(10, e)) { + fractionDigits = maxDigits - e + break; + } + } + const scale = Math.pow(10, fractionDigits) + value = Math.round(value * scale) / scale + return { value, unit } +} \ No newline at end of file diff --git a/src/music/beautify-value.js b/src/music/beautify-value.js new file mode 100644 index 0000000..3b30fe4 --- /dev/null +++ b/src/music/beautify-value.js @@ -0,0 +1,25 @@ +export default function beautifyValue(frequency) { + let maxDigits = 4 + let value = frequency + let unit = "" + if (value > 1e3) { + value /= 1e3 + unit = "k" + } else if (value > 1e6) { + value /= 1e3 + unit = "M" + } else if (value > 1e9) { + value /= 1e3 + unit = "G" + } + let fractionDigits = 1 + for (let e = 0; e < 3; e++) { + if (value <= Math.pow(10, e)) { + fractionDigits = maxDigits - e + break; + } + } + const scale = Math.pow(10, fractionDigits) + value = Math.round(value * scale) / scale + return { value, unit } +} \ No newline at end of file diff --git a/src/music/notes.js b/src/music/notes.js new file mode 100644 index 0000000..d8d0657 --- /dev/null +++ b/src/music/notes.js @@ -0,0 +1,120 @@ + +export class Note { + static LT = '<' + static GT = '>' + static CLOSE = '≈' + static EQ = '=' + static NONE = '!' + + frequency + precision + match + name + octave + color + index + + constructor({frequency = null, match = null, name = "", octave = null, color = null, precision=Note.NONE, index = 0} = {}) { + this.frequency = frequency + this.precision = precision + this.match = match + this.name = name + this.octave = octave + this.color = color + this.index = index + } +} + +export const ALTERNATIVE_NOTE_NAMES = (() => { + const greekAlphabet = 'αβγδεζηθικλμνξοπρςτυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ'.split('') + return [...greekAlphabet, ...greekAlphabet.map((value) => `${value}'`)] +})() + +export const PIANO_KEYS = (() => { + const from = 440 + const min = -4 + const zeroOctave = -5 + const max = 5 + const names = ["a", "a#", "b", "c", "c#", "d", "d#", "e", "f", "f#", "g", "g#"] + const colors = [0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1] + const octaveOffset = 9 + let arr = [] + let index = 0 + for (let octave = min; octave < max; octave++) { + let base = from * Math.pow(2, octave) + for (let note = 0; note < 12; note++) { + arr.push(new Note({ + match: base * Math.pow(2, note / 12), + name: names[note], + octave: Math.round(((octave - zeroOctave) * 12 + note - octaveOffset) / 12), + color: colors[note], + index + })) + index++ + } + } + return arr +})() + +export const OCTAVES = (() => { + const octaves = [] + let last = null + PIANO_KEYS.forEach(key => { + if (key.octave !== last) { + octaves.push(key) + last = key.octave + } + }) + return octaves +})() + +export const FREQUENCY_MAP = (() => { + const map = new Map() + PIANO_KEYS.forEach(key => { + map.set(Math.round(key.match * 100) / 100, key) + }) + return map +})() + +export function getOctave(frequency) { + if (frequency < OCTAVES[0].frequency) return null + for (let i = 0; i < OCTAVES.length; i++) { + if (frequency <= OCTAVES[i].frequency) return OCTAVES[i].octave - 1 + } + return null +} + +export function findClosestNote(frequency) { + let previousDelta = Number.MAX_SAFE_INTEGER + let previous + for (let i=0; i frequency) { + if (delta < previousDelta) return key + return previous + } + previousDelta = delta + previous = key + } + return previous +} + +export function getNoteByIndex(index) { + return new Note(PIANO_KEYS[index]) +} + +export function getNote(frequency) { + const closest = new Note(findClosestNote(frequency)) + closest.frequency = frequency + if (Math.abs(closest.match - frequency) < .001) { + closest.precision = Note.EQ + } else if (Math.abs(closest.match - frequency) < .5) { + closest.precision = Note.CLOSE + } else if (frequency > closest.match) { + closest.precision = Note.GT + } else if (frequency < closest.match) { + closest.precision = Note.LT + } + return closest +} diff --git a/src/storage/db.js b/src/storage/db.js new file mode 100644 index 0000000..c66b815 --- /dev/null +++ b/src/storage/db.js @@ -0,0 +1,133 @@ +import clone from "../data/clone.js" +import Signal from "../glue/signal.js" +import generateTree from "../model/generate-tree.js" + +export default class DB { + + #db + #name + #version + + constructor(name, version) { + this.#name = name + this.#version = version + } + + open() { + return new Promise((resolve, reject)=>{ + const openRequest = indexedDB.open(this.#name, this.#version) + openRequest.onerror = (event) => { + reject('Error loading database.') + } + openRequest.onupgradeneeded = (event) => { + const db = event.target.result + const objectStore = db.createObjectStore("sessions", { keyPath: "id" }) + objectStore.createIndex("name", "name", { unique: false }) + objectStore.createIndex("changed", "changed", { unique: false }) + objectStore.createIndex("created", "created", { unique: false }) + } + openRequest.onsuccess = (event) => { + this.#db = openRequest.result + resolve(openRequest.result) + } + }) + } + + write(session) { + return new Promise((resolve, reject)=> { + const tx = this.#db.transaction(['sessions'], "readwrite") + const store = tx.objectStore("sessions") + const sessionObject = clone(session) + sessionObject.tree = generateTree(session) + sessionObject.changed = Date.now() + if (!sessionObject.created) sessionObject.created = Date.now() + store.put(sessionObject) + tx.oncomplete = () => { + resolve() + Signal.broadcast(this, {property: "sessions"}) + } + tx.onerror = () => { + reject(tx.error) + } + }) + } + + read(id) { + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions'); + const query = store.get(id) + query.onsuccess = () => { + resolve(query.result) + } + query.onerror = () => { + reject(tx.error) + } + + }) + } + + list() { + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions') + const index = store.index('created') + const cursor = index.openCursor(null, 'prev') + const result = [] + cursor.onsuccess = (event) => { + const currentCursor = event.target.result; + if (!currentCursor) return resolve(result) + const { id, name, tree, changed } = currentCursor.value + result.push({id, name, tree, changed}) + currentCursor.continue() + } + + cursor.onerror = (event) => { + reject() + } + + }) + } + + delete(id) { + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions'); + const request = store.delete(id) + tx.oncomplete = () => { + resolve() + Signal.broadcast(this, {property: "sessions"}) + } + tx.onerror = () => { + reject(tx.error) + } + + }) + } + + recent() { + + return new Promise((resolve, reject)=>{ + const tx = this.#db.transaction(['sessions'], 'readwrite') + const store = tx.objectStore('sessions') + const index = store.index('changed') + const cursor = index.openCursor(null, 'prev') + + cursor.onsuccess = (event) => { + const currentCursor = event.target.result + if (currentCursor) resolve(currentCursor.value) + else resolve() + } + + cursor.onerror = (event) => { + reject() + } + + }) + } + + close() { + this.#db.close() + } + +} \ No newline at end of file diff --git a/src/utils/camel-to-kebab.js b/src/utils/camel-to-kebab.js new file mode 100644 index 0000000..44a6c1c --- /dev/null +++ b/src/utils/camel-to-kebab.js @@ -0,0 +1,5 @@ +export default function camelToKebab(str) { + if (!str) return null + if (str === str.toUpperCase()) return str.toLowerCase() + return str.split(/(?=[A-Z])/).join('-').toLowerCase() +} \ No newline at end of file diff --git a/src/utils/random-name.js b/src/utils/random-name.js new file mode 100644 index 0000000..a66b57b --- /dev/null +++ b/src/utils/random-name.js @@ -0,0 +1,35 @@ +import randomWord from "./random-word.js" + +function biasedRandomNumber(min, max, bias) { + const baseRandom = Math.random(); + const biasedRandom = Math.pow(baseRandom, 1/bias); + const range = max - min; + const scaledRandom = Math.floor(biasedRandom * range) + min; + + return Math.min(Math.max(scaledRandom, min), max); +} + +export default function randomName() { + let name = "" + const minChars = 5 + const maxChars = 13 + const minWordLength = 2 + const maxWordLength = 9 + const nameLen = biasedRandomNumber(minChars, maxChars, 2) + // Math.round(minChars + Math.random() * (maxChars-minChars)) + while (name.length < nameLen) { + if (name.length) name += " " + let wordLen + let available = (nameLen - name.length) + wordLen = biasedRandomNumber(minWordLength, maxWordLength, 3) + if (available < minWordLength*2+1) { + wordLen = available + } else if (available > wordLen) {// Math.round(minWordLength + Math.random() * (maxWordLength-minWordLength)) + wordLen = Math.min(available - minWordLength - 1, wordLen ) + } + const word = randomWord(wordLen) + name += word + } + name = name.split(" ").sort(()=>{return (Math.random()>0.5)?-1:1}).join(" ") + return name +} \ No newline at end of file diff --git a/src/utils/random-pick.js b/src/utils/random-pick.js new file mode 100644 index 0000000..564af35 --- /dev/null +++ b/src/utils/random-pick.js @@ -0,0 +1,3 @@ +export default function randomPick(array) { + return array[Math.floor(Math.random() * array.length)] +} \ No newline at end of file diff --git a/src/utils/random-word.js b/src/utils/random-word.js new file mode 100644 index 0000000..f3d0bf0 --- /dev/null +++ b/src/utils/random-word.js @@ -0,0 +1,38 @@ +import randomPick from "./random-pick.js"; + +const syllableType = { + "vowel":["ai", "ay", "ei", "ey", "oi", "oy", "ou", "au", "ea", "ee", "ie", "oo", "ue", "ui", "eu", "oa", "eo", "iu", "ae", "ui", "ie", "uo", "ey", "a", "e", "i", "o", "u", "y"], + "consonant": ["str", "scr", "sch", "spr", "spl", "thr", "shr", "squ", "sm", "sn", "sp", "st", "sk", "sl", "sw", "bl", "cl", "fl", "gl", "pl", "tl", "br", "cr", "dr", "fr", "gr", "pr", "tr", "ch", "sh", "th", "wh", "kn", "gn", "b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","z"], +} + +export default function randomWord(chars) { + let word = ""; + let lastType + + while (word.length < chars) { + let type + if (word.length == 0) { + type = randomPick(["vowel", "consonant"]) + } else if (lastType === "consonant") { + type = "vowel" + } else if (lastType === "vowel") { + type = "consonant" + } else { + type = "vowel" + } + + let available = chars-word.length + let maxSyllableLength = available + if (type === "consonant" && available == 3) maxSyllableLength = 2 + else if (type === "consonant" && available == 2) maxSyllableLength = 1 + const syllable = randomPick( + syllableType[type].filter((syllable)=>{ + return syllable.length <= maxSyllableLength + }) + ) + word += syllable + lastType = type + } + word = word.charAt(0).toUpperCase() + word.slice(1) + return word +} \ No newline at end of file diff --git a/src/wave-spline/find-closest.js b/src/wave-spline/find-closest.js new file mode 100644 index 0000000..025620d --- /dev/null +++ b/src/wave-spline/find-closest.js @@ -0,0 +1,16 @@ +import calculateDistance from "../math/calculate-distance.js" + +export default function findClosest(p, points, weight = {x:1, y:1}) { + let best = Number.POSITIVE_INFINITY + let result = null + const len = points.length + for (let i = 0; i x ) { + b = i + break + } + a = i + } + return [points[a], points[b]] +} \ No newline at end of file diff --git a/src/wave-spline/process-wave-spline-points.js b/src/wave-spline/process-wave-spline-points.js new file mode 100644 index 0000000..3ea4db3 --- /dev/null +++ b/src/wave-spline/process-wave-spline-points.js @@ -0,0 +1,39 @@ +import compareFloat from "../math/compare-float.js" +import transformWaveSplinePoint from "./transform-wave-spline-point.js" + +export default function processWaveSplinePoints(points, cx=.5, cy=.5, sx=1, sy=1, rx=1, ry=1) { + + const len = points.length + let out = [] + let point = {x: -1, y: 0, e: 0} + let x = -1 + let y = 0 + let e = 0 + let stackCount = 0 + let cur + for (let i = 0; i cx + rx) return point + return { + x: ((point.x-cx)*sx+cx), + y: ((point.y-cy)*sy+cy), + e: point.e + } +} \ No newline at end of file