Repository: stevenjoezhang/live2d-widget
Branch: master
Commit: fa963c631377
Files: 82
Total size: 598.7 KB
Directory structure:
gitextract_2gq63twy/
├── .github/
│ └── workflows/
│ ├── linter.yml
│ └── tester.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.yaml
├── LICENSE
├── README.en.md
├── README.md
├── build/
│ ├── cubism2/
│ │ ├── LAppDefine.d.ts
│ │ ├── LAppDefine.js
│ │ ├── LAppLive2DManager.d.ts
│ │ ├── LAppLive2DManager.js
│ │ ├── LAppModel.d.ts
│ │ ├── LAppModel.js
│ │ ├── Live2DFramework.d.ts
│ │ ├── Live2DFramework.js
│ │ ├── PlatformManager.d.ts
│ │ ├── PlatformManager.js
│ │ ├── index.d.ts
│ │ ├── index.js
│ │ └── utils/
│ │ ├── MatrixStack.d.ts
│ │ ├── MatrixStack.js
│ │ ├── ModelSettingJson.d.ts
│ │ └── ModelSettingJson.js
│ ├── cubism5/
│ │ ├── index.d.ts
│ │ └── index.js
│ ├── drag.d.ts
│ ├── drag.js
│ ├── icons.d.ts
│ ├── icons.js
│ ├── index.d.ts
│ ├── index.js
│ ├── logger.d.ts
│ ├── logger.js
│ ├── message.d.ts
│ ├── message.js
│ ├── model.d.ts
│ ├── model.js
│ ├── tools.d.ts
│ ├── tools.js
│ ├── utils.d.ts
│ ├── utils.js
│ ├── waifu-tips.d.ts
│ ├── waifu-tips.js
│ ├── widget.d.ts
│ └── widget.js
├── demo/
│ ├── chat.html
│ ├── demo.html
│ └── login.html
├── dist/
│ ├── autoload.js
│ ├── chunk/
│ │ ├── index.js
│ │ └── index2.js
│ ├── waifu-tips.js
│ ├── waifu-tips.json
│ └── waifu.css
├── eslint.config.js
├── package.json
├── renovate.json
├── rollup.config.js
├── src/
│ ├── cubism2/
│ │ ├── LAppDefine.js
│ │ ├── LAppLive2DManager.js
│ │ ├── LAppModel.js
│ │ ├── Live2DFramework.js
│ │ ├── PlatformManager.js
│ │ ├── index.js
│ │ └── utils/
│ │ ├── MatrixStack.js
│ │ └── ModelSettingJson.js
│ ├── cubism5/
│ │ └── index.js
│ ├── drag.ts
│ ├── icons.ts
│ ├── index.ts
│ ├── logger.ts
│ ├── message.ts
│ ├── model.ts
│ ├── tools.ts
│ ├── types/
│ │ ├── index.d.ts
│ │ ├── live2dApi.d.ts
│ │ └── window.d.ts
│ ├── utils.ts
│ ├── waifu-tips.ts
│ └── widget.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/linter.yml
================================================
name: Linter
on: [push, pull_request]
jobs:
linter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Use Node.js
uses: actions/setup-node@v6
- name: Install Dependencies
run: npm install
- run: npm run eslint
================================================
FILE: .github/workflows/tester.yml
================================================
name: Tester
on: [push, pull_request]
jobs:
tester:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
fail-fast: false
steps:
- uses: actions/checkout@v5
with:
repository: hexojs/hexo-starter
- name: Use Node.js
uses: actions/setup-node@v6
- name: Install Dependencies
run: npm install
- name: Test
run: npm run build
================================================
FILE: .gitignore
================================================
package-lock.json
node_modules/
.DS_Store
.idea/
.vscode/
backup/
src/CubismSdkForWeb-*/
build/CubismSdkForWeb-*/
================================================
FILE: .prettierignore
================================================
node_modules
dist
================================================
FILE: .prettierrc.yaml
================================================
tabWidth: 2
semi: true
singleQuote: true
jsxSingleQuote: true
trailingComma: all
endOfLine: crlf
================================================
FILE: LICENSE
================================================
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
.
================================================
FILE: README.en.md
================================================
# Live2D Widget






[中文](README.md)
## Features
- Add Live2D widget to web page
- Lightweight, with no runtime dependencies other than Live2D Cubism Core
- Core code is written in TypeScript, making it easy to integrate
*Note: The character models above are for demonstration purposes only and are not included in this repository.*
You can also check out example web pages:
- Check the effect in the lower left corner of [Mimi's Blog](https://zhangshuqiao.org)
- [demo/demo.html](https://live2d-widget.pages.dev/demo/demo) to demonstrate basic functionality
- [demo/login.html](https://live2d-widget.pages.dev/demo/login) to imitate the login interface of NPM
## Usage
If you are a beginner or only need the basic functionality, you can simply add the following line of code to the `head` or `body` of your HTML page to load the widget:
```html
```
The placement of the code depends on how your website is built. For example, if you are using [Hexo](https://hexo.io), you need to add the above code to the template file of your theme. The modification process is similar for pages generated using various template engines.
If your website uses PJAX, since the widget does not need to be refreshed on every page, make sure to place the script outside the PJAX refresh area.
**However, we strongly recommend configuring the widget yourself to make it more suitable for your website!**
If you are interested in customizing the widget, please refer to the detailed instructions below.
## Configuration
You can refer to the source code of `dist/autoload.js` to see the available configuration options. `autoload.js` will automatically load two files: `waifu.css` and `waifu-tips.js`. `waifu-tips.js` creates the `initWidget` function, which is the main function for loading the widget. The `initWidget` function accepts an object-type parameter as the configuration for the widget. The following are the available options:
| Option | Type | Default Value | Description |
| ------ | ---- | ------------- | ----------- |
| `waifuPath` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/waifu-tips.json` | Path to the widget resources, can be modified |
| `cdnPath` | `string` | `https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/` | CDN path |
| `cubism2Path` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/live2d.min.js` | Path to Cubism 2 Core |
| `cubism5Path` | `string` | `https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js` | Path to Cubism 5 Core |
| `modelId` | `number` | `0` | Default model id |
| `tools` | `string[]` | see `autoload.js` | Buttons of the loaded tools |
| `drag` | `boolean` | `false` | Make the widget draggable |
| `logLevel` | `string` | `error` | Log level: `error`, `warn`, `info`, `trace` |
## Model Repository
This repository does not include any models. You need to configure a separate model repository and set it via the `cdnPath` option.
Older versions of the `initWidget` function supported the `apiPath` parameter, which required users to set up their own backend. You can refer to [live2d_api](https://github.com/fghrsh/live2d_api) for details. The backend interface would integrate model resources and dynamically generate JSON description files. Since version 1.0, these features have been implemented on the frontend, so a dedicated `apiPath` is no longer required. All model resources can be provided statically. As long as `model_list.json` and the corresponding `textures.cache` for each model exist, features such as outfit changing are supported.
## Development
If the options provided in the "Configuration" section above are not enough to meet your needs, you can make modifications yourself. The directory structure of this repository is as follows:
- `src` directory contains the TypeScript code for each component, e.g. the button and dialog box.
- `build` directory contains files generated from the source code in `src` (please do not modify them directly!)
- `dist` directory contains the files that can be directly used on web pages after packaging, including:
- `autoload.js` is used to automatically load other resources such as style sheets.
- `waifu-tips.js` is automatically generated by `build/waifu-tips.js` and it is not recommended to modify it directly.
- `waifu.css` is the style sheet for the widget.
- `waifu-tips.json` defines the triggering conditions (`selector`, CSS selector) and the displayed text when triggered (`text`).
By default, the CSS selector rules in `waifu-tips.json` are effective for the Hexo [NexT theme](https://github.com/next-theme/hexo-theme-next), but you may need to modify or add new content to make it suitable for your own website.
**Warning: The content in `waifu-tips.json` may not be suitable for all age groups or appropriate to access during work. Please ensure their suitability when using them.**
To deploy the development testing environment of this project locally, you need to install Node.js and npm, then execute the following commands:
```bash
git clone https://github.com/stevenjoezhang/live2d-widget.git
npm install
```
If you need to use Cubism 3 or newer models, please download and extract the Cubism SDK for Web separately into the `src` directory, for example, `src/CubismSdkForWeb-5-r.4`. Due to Live2D license agreements (including the Live2D Proprietary Software License Agreement and Live2D Open Software License Agreement), this project cannot include the source code of Cubism SDK for Web.
If you only need to use Cubism 2 models, you can skip this step. The code in this repository complies with the Redistributable Code terms of the Live2D license agreements.
Once completed, use the following command to compile and bundle the project.
```bash
npm run build
```
The TypeScript code in the `src` directory is compiled into the `build` directory, and the code in the `build` directory is further bundled into the `dist` directory.
To support both Cubism 2 and Cubism 3 (and newer) models while minimizing code size, Cubism Core and related code are loaded dynamically based on the detected model version.
## Deploy
After making modifications locally, you can deploy the modified project on a server or load it via a CDN. To make it easier to customize, you can fork this repository and push your modified content to your own repository using `git push`.
### Using jsDelivr CDN
To load forked repository via jsDelivr, the usage method becomes:
```html
```
Replace `username` with your GitHub username. To ensure the content of the CDN is refreshed correctly, you need to create a new git tag and push it to the GitHub repository. Otherwise, `@latest` in the URL will still point to the previous version. Additionally, CDN itself has caching, so the changes may take some time to take effect.
### Using Cloudflare Pages
You can also deploy using Cloudflare Pages. Create a new project in Cloudflare Pages and select your forked repository. Then, set the build command to `npm run build`. Once configured, Cloudflare Pages will automatically build and deploy your project.
### Self-host
Alternatively, you can directly host these files on your server instead of loading them via CDN.
- Clone the forked repository onto your server, or upload the local files to the website directory on the server using `ftp` or similar methods.
- If you are deploying a static blog using Hexo or similar tools, place the code of this project in the blog's source file directory (e.g., the `source` directory). When redeploying the blog, the relevant files will be automatically uploaded to the corresponding paths. To prevent these files from being incorrectly modified by Hexo plugins, you may need to set `skip_render`.
Afterwards, the entire project can be accessed through your domain name. You can try opening the `autoload.js` and `live2d.min.js` files in your browser and confirm that their content is complete and correct.
If everything is normal, you can proceed to modify the constant `live2d_path` in `autoload.js` to the URL of the `dist` directory. For example, if you can access `live2d.min.js` through the following URL:
```
https://example.com/path/to/live2d-widget/dist/live2d.min.js
```
then modify the value of `live2d_path` to:
```
https://example.com/path/to/live2d-widget/dist/
```
Make sure to include the trailing `/` in the path.
Once done, add the following code to the interface where you want to add the live2d-widget:
```html
```
This will load the widget.
## Thanks
> Thanks to [BrowserStack](https://www.browserstack.com/) for providing the infrastructure that allows us to test in real browsers!
> Thanks to jsDelivr for providing public CDN service.
Thanks fghrsh for providing API service.
Thanks to [Hitokoto](https://hitokoto.cn) for providing the sentence API.
When you click on the paper airplane button of the virtual assistant, a hidden surprise will appear. This feature is from [WebsiteAsteroids](http://www.websiteasteroids.com).
## More
The code is modified based on this blog post:
https://www.fghrsh.net/post/123.html
For more information, you can refer to the following links:
https://nocilol.me/archives/lab/add-dynamic-poster-girl-with-live2d-to-your-blog-02
https://github.com/guansss/pixi-live2d-display
For more models:
https://github.com/zenghongtu/live2d-model-assets
In addition to that, there are desktop versions available:
https://github.com/TSKI433/hime-display
https://github.com/amorist/platelet
https://github.com/akiroz/Live2D-Widget
https://github.com/zenghongtu/PPet
https://github.com/LikeNeko/L2dPetForMac
And also Wallpaper Engine:
https://github.com/guansss/nep-live2d
Official Live2D websites:
https://www.live2d.com/en/
## License
This repository does not contain any models. The copyrights of all Live2D models, images, and motion data used for demonstration purposes belong to their respective original authors. They are provided for research and learning purposes only and should not be used for commercial purposes.
The code in this repository (excluding parts covered by the Live2D Proprietary Software License and the Live2D Open Software License) is released under the GNU General Public License v3
http://www.gnu.org/licenses/gpl-3.0.html
Please comply with the relevant licenses when using any Live2D-related code:
License for Live2D Cubism SDK 2.1:
[Live2D SDK License Agreement (Public)](https://docs.google.com/document/d/10tz1WrycskzGGBOhrAfGiTSsgmyFy8D9yHx9r_PsN8I/)
License for Live2D Cubism SDK 5:
Live2D Cubism Core is provided under the Live2D Proprietary Software License.
https://www.live2d.com/eula/live2d-proprietary-software-license-agreement_en.html
Live2D Cubism Components are provided under the Live2D Open Software License.
https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html
## Update Log
Starting from January 1, 2020, this project no longer depends on jQuery.
Starting from November 1, 2022, this project no longer requires users to separately load Font Awesome.
================================================
FILE: README.md
================================================
# Live2D Widget






[English](README.en.md)
## 特性
- 在网页中添加 Live2D 看板娘
- 轻量级,除 Live2D Cubism Core 外无其他运行时依赖
- 核心代码由 TypeScript 编写,易于集成
*注:以上人物模型仅供展示之用,本仓库并不包含任何模型。*
你也可以查看示例网页:
- 在 [米米的博客](https://zhangshuqiao.org) 的左下角可查看效果
- [demo/demo.html](https://live2d-widget.pages.dev/demo/demo),展现基础功能
- [demo/login.html](https://live2d-widget.pages.dev/demo/login),仿 NPM 的登陆界面
## 使用
如果你是小白,或者只需要最基础的功能,那么只用将这一行代码加入 html 页面的 `head` 或 `body` 中,即可加载看板娘:
```html
```
添加代码的位置取决于你的网站的构建方式。例如,如果你使用的是 [Hexo](https://hexo.io),那么需要在主题的模版文件中添加以上代码。对于用各种模版引擎生成的页面,修改方法类似。
如果网站启用了 PJAX,由于看板娘不必每页刷新,需要注意将该脚本放到 PJAX 刷新区域之外。
**但是!我们强烈推荐自己进行配置,让看板娘更加适合你的网站!**
如果你有兴趣自己折腾的话,请看下面的详细说明。
## 配置
你可以对照 `dist/autoload.js` 的源码查看可选的配置项目。`autoload.js` 会自动加载两个文件:`waifu.css` 和 `waifu-tips.js`。`waifu-tips.js` 会创建 `initWidget` 函数,这就是加载看板娘的主函数。`initWidget` 函数接收一个 Object 类型的参数,作为看板娘的配置。以下是配置选项:
| 选项 | 类型 | 默认值 | 说明 |
| - | - | - | - |
| `waifuPath` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/waifu-tips.json` | 看板娘资源路径,可自行修改 |
| `cdnPath` | `string` | `https://fastly.jsdelivr.net/gh/fghrsh/live2d_api/` | CDN 路径 |
| `cubism2Path` | `string` | `https://fastly.jsdelivr.net/npm/live2d-widgets@1/dist/live2d.min.js` | Cubism 2 Core 路径 |
| `cubism5Path` | `string` | `https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js` | Cubism 5 Core 路径 |
| `modelId` | `number` | `0` | 默认模型 id |
| `tools` | `string[]` | 见 `autoload.js` | 加载的小工具按钮 |
| `drag` | `boolean` | `false` | 支持拖动看板娘 |
| `logLevel` | `string` | `error` | 日志等级,支持 `error`,`warn`,`info`,`trace` |
## 模型仓库
本仓库中并不包含任何模型,需要单独配置模型仓库,并通过 `cdnPath` 选项进行设置。
旧版本的 `initWidget` 函数支持 `apiPath` 参数,这要求用户自行搭建后端,可以参考 [live2d_api](https://github.com/fghrsh/live2d_api)。后端接口会对模型资源进行整合并动态生成 JSON 描述文件。自 1.0 版本起,相关功能已通过前端实现,因此不再需要专门的 `apiPath`,所有模型资源都可通过静态方式提供。只要存在 `model_list.json` 和模型对应的 `textures.cache`,即可支持换装等功能。
## 开发
如果以上「配置」部分提供的选项还不足以满足你的需求,那么你可以自己进行修改。本仓库的目录结构如下:
- `src` 目录下包含了各个组件的 TypeScript 源代码,例如按钮和对话框等;
- `build` 目录下包含了基于 `src` 中源代码构建后的文件(请不要直接修改!);
- `dist` 目录下包含了进一步打包后网页直接可用的文件,其中:
- `autoload.js` 用于自动加载其它资源,例如样式表等;
- `waifu-tips.js` 是由 `build/waifu-tips.js` 自动打包生成的,不建议直接修改;
- `waifu.css` 是看板娘的样式表;
- `waifu-tips.json` 中定义了触发条件(`selector`,CSS 选择器)和触发时显示的文字(`text`)。
`waifu-tips.json` 中默认的 CSS 选择器规则是对 Hexo 的 [NexT 主题](https://github.com/next-theme/hexo-theme-next) 有效的,为了适用于你自己的网页,可能需要自行修改,或增加新内容。
**警告:`waifu-tips.json` 中的内容可能不适合所有年龄段,或不宜在工作期间访问。在使用时,请自行确保它们是合适的。**
要在本地部署本项目的开发测试环境,你需要安装 Node.js 和 npm,然后执行以下命令:
```bash
git clone https://github.com/stevenjoezhang/live2d-widget.git
npm install
```
如果需要使用 Cubism 3 及更新的模型,请单独下载并解压 Cubism SDK for Web 到 `src` 目录下,例如 `src/CubismSdkForWeb-5-r.4`。受 Live2D 许可协议(包括 Live2D Proprietary Software License Agreement 和 Live2D Open Software License Agreement)限制,本项目无法包含 Cubism SDK for Web 的源码。
如果只需要使用 Cubism 2 版本的模型,可以跳过此步骤。本仓库使用的代码满足 Live2D 许可协议中 Redistributable Code 相关条款。
完成后,使用以下命令进行编译和打包。
```bash
npm run build
```
`src` 目录中的 TypeScript 代码会被编译到 `build` 目录中,`build` 目录中的代码会被进一步打包到 `dist` 目录中。
为了能够兼容 Cubism 2 和 Cubism 3 及更新的模型,并减小代码体积,Cubism Core 及相关的代码会根据检测到的模型版本动态加载。
## 部署
在本地完成了修改后,你可以将修改后的项目部署在自己的服务器上,或者通过 CDN 加载。为了方便自定义有关内容,可以把这个仓库 Fork 一份,然后把修改后的内容通过 git push 到你的仓库中。
### 使用 jsDelivr CDN
如果要通过 jsDelivr 加载 Fork 后的仓库,使用方法对应地变为
```html
```
将此处的 `username` 替换为你的 GitHub 用户名。为了使 CDN 的内容正常刷新,需要创建新的 git tag 并推送至 GitHub 仓库中,否则此处的 `@latest` 仍然指向更新前的文件。此外 CDN 本身存在缓存,因此改动可能需要一定的时间生效。
### 使用 Cloudflare Pages
也可以使用 Cloudflare Pages 来部署。在 Cloudflare Pages 中创建一个新的项目,选择你 Fork 的仓库。接下来,设置构建命令为 `npm run build`。完成后,Cloudflare Pages 会自动构建并部署你的项目。
### Self-host
你也可以直接把这些文件放到服务器上,而不是通过 CDN 加载。
- 可以把修改后的代码仓库克隆到服务器上,或者通过 `ftp` 等方式将本地文件上传到服务器的网站的目录下;
- 如果你是通过 Hexo 等工具部署的静态博客,请把本项目的代码放在博客源文件目录下(例如 `source` 目录)。重新部署博客时,相关文件就会自动上传到对应的路径下。为了避免这些文件被 Hexo 插件错误地修改,可能需要设置 `skip_render`。
这样,整个项目就可以通过你的域名访问了。不妨试试能否正常地通过浏览器打开 `autoload.js` 和 `live2d.min.js` 等文件,并确认这些文件的内容是完整和正确的。
一切正常的话,接下来修改 `autoload.js` 中的常量 `live2d_path` 为 `dist` 目录的 URL 即可。比如说,如果你能够通过
```
https://example.com/path/to/live2d-widget/dist/live2d.min.js
```
访问到 `live2d.min.js`,那么就把 `live2d_path` 的值修改为
```
https://example.com/path/to/live2d-widget/dist/
```
路径末尾的 `/` 一定要加上。
完成后,在你要添加看板娘的界面加入
```html
```
就可以加载了。
## 鸣谢
> 感谢 BrowserStack 容许我们在真实的浏览器中测试此项目。
> Thanks to [BrowserStack](https://www.browserstack.com/) for providing the infrastructure that allows us to test in real browsers!
> 感谢 jsDelivr 提供的 CDN 服务。
> Thanks jsDelivr for providing public CDN service.
感谢 fghrsh 提供的 API 服务。
感谢 [一言](https://hitokoto.cn) 提供的语句接口。
点击看板娘的纸飞机按钮时,会出现一个彩蛋,这来自于 [WebsiteAsteroids](http://www.websiteasteroids.com)。
## 更多
代码自这篇博文魔改而来:
https://www.fghrsh.net/post/123.html
更多内容可以参考:
https://nocilol.me/archives/lab/add-dynamic-poster-girl-with-live2d-to-your-blog-02
https://github.com/guansss/pixi-live2d-display
更多模型仓库:
https://github.com/zenghongtu/live2d-model-assets
除此之外,还有桌面版本:
https://github.com/TSKI433/hime-display
https://github.com/amorist/platelet
https://github.com/akiroz/Live2D-Widget
https://github.com/zenghongtu/PPet
https://github.com/LikeNeko/L2dPetForMac
以及 Wallpaper Engine:
https://github.com/guansss/nep-live2d
Live2D 官方网站:
https://www.live2d.com/en/
## 许可证
本仓库并不包含任何模型,用作展示的所有 Live2D 模型、图片、动作数据等版权均属于其原作者,仅供研究学习,不得用于商业用途。
本仓库的代码(不包括受 Live2D Proprietary Software License 和 Live2D Open Software License 约束的部分)基于 GNU General Public License v3 协议开源
http://www.gnu.org/licenses/gpl-3.0.html
Live2D 相关代码的使用请遵守对应的许可:
Live2D Cubism SDK 2.1 的许可证:
[Live2D SDK License Agreement (Public)](https://docs.google.com/document/d/10tz1WrycskzGGBOhrAfGiTSsgmyFy8D9yHx9r_PsN8I/)
Live2D Cubism SDK 5 的许可证:
Live2D Cubism Core は Live2D Proprietary Software License で提供しています。
https://www.live2d.com/eula/live2d-proprietary-software-license-agreement_cn.html
Live2D Cubism Components は Live2D Open Software License で提供しています。
https://www.live2d.com/eula/live2d-open-software-license-agreement_cn.html
## 更新日志
2020年1月1日起,本项目不再依赖于 jQuery。
2022年11月1日起,本项目不再需要用户单独加载 Font Awesome。
================================================
FILE: build/cubism2/LAppDefine.d.ts
================================================
export default LAppDefine;
declare namespace LAppDefine {
let VIEW_MAX_SCALE: number;
let VIEW_MIN_SCALE: number;
let VIEW_LOGICAL_LEFT: number;
let VIEW_LOGICAL_RIGHT: number;
let VIEW_LOGICAL_MAX_LEFT: number;
let VIEW_LOGICAL_MAX_RIGHT: number;
let VIEW_LOGICAL_MAX_BOTTOM: number;
let VIEW_LOGICAL_MAX_TOP: number;
let PRIORITY_NONE: number;
let PRIORITY_IDLE: number;
let PRIORITY_NORMAL: number;
let PRIORITY_FORCE: number;
let MOTION_GROUP_IDLE: string;
let MOTION_GROUP_TAP_BODY: string;
let MOTION_GROUP_FLICK_HEAD: string;
let MOTION_GROUP_PINCH_IN: string;
let MOTION_GROUP_PINCH_OUT: string;
let MOTION_GROUP_SHAKE: string;
let HIT_AREA_HEAD: string;
let HIT_AREA_BODY: string;
}
================================================
FILE: build/cubism2/LAppDefine.js
================================================
const LAppDefine = {
VIEW_MAX_SCALE: 1.5,
VIEW_MIN_SCALE: 1,
VIEW_LOGICAL_LEFT: -1,
VIEW_LOGICAL_RIGHT: 1,
VIEW_LOGICAL_MAX_LEFT: -2,
VIEW_LOGICAL_MAX_RIGHT: 2,
VIEW_LOGICAL_MAX_BOTTOM: -2,
VIEW_LOGICAL_MAX_TOP: 2,
PRIORITY_NONE: 0,
PRIORITY_IDLE: 1,
PRIORITY_NORMAL: 2,
PRIORITY_FORCE: 3,
MOTION_GROUP_IDLE: 'idle',
MOTION_GROUP_TAP_BODY: 'tap_body',
MOTION_GROUP_FLICK_HEAD: 'flick_head',
MOTION_GROUP_PINCH_IN: 'pinch_in',
MOTION_GROUP_PINCH_OUT: 'pinch_out',
MOTION_GROUP_SHAKE: 'shake',
HIT_AREA_HEAD: 'head',
HIT_AREA_BODY: 'body',
};
export default LAppDefine;
================================================
FILE: build/cubism2/LAppLive2DManager.d.ts
================================================
export default LAppLive2DManager;
declare class LAppLive2DManager {
model: LAppModel;
reloading: boolean;
getModel(): LAppModel;
releaseModel(gl: any): void;
changeModel(gl: any, modelSettingPath: any): Promise;
changeModelWithJSON(gl: any, modelSettingPath: any, modelSetting: any): Promise;
setDrag(x: any, y: any): void;
maxScaleEvent(): void;
minScaleEvent(): void;
tapEvent(x: any, y: any): boolean;
}
import LAppModel from './LAppModel.js';
================================================
FILE: build/cubism2/LAppLive2DManager.js
================================================
import { Live2DFramework } from './Live2DFramework.js';
import LAppModel from './LAppModel.js';
import PlatformManager from './PlatformManager.js';
import LAppDefine from './LAppDefine.js';
import logger from '../logger.js';
class LAppLive2DManager {
constructor() {
this.model = null;
this.reloading = false;
Live2D.init();
Live2DFramework.setPlatformManager(new PlatformManager());
}
getModel() {
return this.model;
}
releaseModel(gl) {
if (this.model) {
this.model.release(gl);
this.model = null;
}
}
async changeModel(gl, modelSettingPath) {
return new Promise((resolve, reject) => {
if (this.reloading)
return;
this.reloading = true;
const oldModel = this.model;
const newModel = new LAppModel();
newModel.load(gl, modelSettingPath, () => {
if (oldModel) {
oldModel.release(gl);
}
this.model = newModel;
this.reloading = false;
resolve();
});
});
}
async changeModelWithJSON(gl, modelSettingPath, modelSetting) {
if (this.reloading)
return;
this.reloading = true;
const oldModel = this.model;
const newModel = new LAppModel();
await newModel.loadModelSetting(modelSettingPath, modelSetting);
if (oldModel) {
oldModel.release(gl);
}
this.model = newModel;
this.reloading = false;
}
setDrag(x, y) {
if (this.model) {
this.model.setDrag(x, y);
}
}
maxScaleEvent() {
logger.trace('Max scale event.');
if (this.model) {
this.model.startRandomMotion(LAppDefine.MOTION_GROUP_PINCH_IN, LAppDefine.PRIORITY_NORMAL);
}
}
minScaleEvent() {
logger.trace('Min scale event.');
if (this.model) {
this.model.startRandomMotion(LAppDefine.MOTION_GROUP_PINCH_OUT, LAppDefine.PRIORITY_NORMAL);
}
}
tapEvent(x, y) {
logger.trace('tapEvent view x:' + x + ' y:' + y);
if (!this.model)
return false;
if (this.model.hitTest(LAppDefine.HIT_AREA_HEAD, x, y)) {
logger.trace('Tap face.');
this.model.setRandomExpression();
}
else if (this.model.hitTest(LAppDefine.HIT_AREA_BODY, x, y)) {
logger.trace('Tap body.');
this.model.startRandomMotion(LAppDefine.MOTION_GROUP_TAP_BODY, LAppDefine.PRIORITY_NORMAL);
}
return true;
}
}
export default LAppLive2DManager;
================================================
FILE: build/cubism2/LAppModel.d.ts
================================================
export default LAppModel;
declare class LAppModel extends L2DBaseModel {
modelHomeDir: string;
modelSetting: ModelSettingJson;
tmpMatrix: any[];
loadJSON(callback: any): void;
loadModelSetting(modelSettingPath: any, modelSetting: any): Promise;
load(gl: any, modelSettingPath: any, callback: any): void;
release(gl: any): void;
preloadMotionGroup(name: any): void;
update(): void;
setRandomExpression(): void;
startRandomMotion(name: any, priority: any): void;
startMotion(name: any, no: any, priority: any): void;
setFadeInFadeOut(name: any, no: any, priority: any, motion: any): void;
setExpression(name: any): void;
draw(gl: any): void;
hitTest(id: any, testX: any, testY: any): boolean;
}
import { L2DBaseModel } from './Live2DFramework.js';
import ModelSettingJson from './utils/ModelSettingJson.js';
================================================
FILE: build/cubism2/LAppModel.js
================================================
import { L2DBaseModel, Live2DFramework, L2DEyeBlink } from './Live2DFramework.js';
import ModelSettingJson from './utils/ModelSettingJson.js';
import LAppDefine from './LAppDefine.js';
import MatrixStack from './utils/MatrixStack.js';
import logger from '../logger.js';
class LAppModel extends L2DBaseModel {
constructor() {
super();
this.modelHomeDir = '';
this.modelSetting = null;
this.tmpMatrix = [];
}
loadJSON(callback) {
const path = this.modelHomeDir + this.modelSetting.getModelFile();
this.loadModelData(path, model => {
for (let i = 0; i < this.modelSetting.getTextureNum(); i++) {
const texPaths = this.modelHomeDir + this.modelSetting.getTextureFile(i);
this.loadTexture(i, texPaths, () => {
if (this.isTexLoaded) {
if (this.modelSetting.getExpressionNum() > 0) {
this.expressions = {};
for (let j = 0; j < this.modelSetting.getExpressionNum(); j++) {
const expName = this.modelSetting.getExpressionName(j);
const expFilePath = this.modelHomeDir +
this.modelSetting.getExpressionFile(j);
this.loadExpression(expName, expFilePath);
}
}
else {
this.expressionManager = null;
this.expressions = {};
}
if (this.eyeBlink == null) {
this.eyeBlink = new L2DEyeBlink();
}
if (this.modelSetting.getPhysicsFile() != null) {
this.loadPhysics(this.modelHomeDir + this.modelSetting.getPhysicsFile());
}
else {
this.physics = null;
}
if (this.modelSetting.getPoseFile() != null) {
this.loadPose(this.modelHomeDir + this.modelSetting.getPoseFile(), () => {
this.pose.updateParam(this.live2DModel);
});
}
else {
this.pose = null;
}
if (this.modelSetting.getLayout() != null) {
const layout = this.modelSetting.getLayout();
if (layout['width'] != null)
this.modelMatrix.setWidth(layout['width']);
if (layout['height'] != null)
this.modelMatrix.setHeight(layout['height']);
if (layout['x'] != null)
this.modelMatrix.setX(layout['x']);
if (layout['y'] != null)
this.modelMatrix.setY(layout['y']);
if (layout['center_x'] != null)
this.modelMatrix.centerX(layout['center_x']);
if (layout['center_y'] != null)
this.modelMatrix.centerY(layout['center_y']);
if (layout['top'] != null)
this.modelMatrix.top(layout['top']);
if (layout['bottom'] != null)
this.modelMatrix.bottom(layout['bottom']);
if (layout['left'] != null)
this.modelMatrix.left(layout['left']);
if (layout['right'] != null)
this.modelMatrix.right(layout['right']);
}
for (let j = 0; j < this.modelSetting.getInitParamNum(); j++) {
this.live2DModel.setParamFloat(this.modelSetting.getInitParamID(j), this.modelSetting.getInitParamValue(j));
}
for (let j = 0; j < this.modelSetting.getInitPartsVisibleNum(); j++) {
this.live2DModel.setPartsOpacity(this.modelSetting.getInitPartsVisibleID(j), this.modelSetting.getInitPartsVisibleValue(j));
}
this.live2DModel.saveParam();
this.preloadMotionGroup(LAppDefine.MOTION_GROUP_IDLE);
this.mainMotionManager.stopAllMotions();
this.setUpdating(false);
this.setInitialized(true);
if (typeof callback == 'function')
callback();
}
});
}
});
}
async loadModelSetting(modelSettingPath, modelSetting) {
this.setUpdating(true);
this.setInitialized(false);
this.modelHomeDir = modelSettingPath.substring(0, modelSettingPath.lastIndexOf('/') + 1);
this.modelSetting = new ModelSettingJson();
this.modelSetting.json = modelSetting;
await new Promise(resolve => this.loadJSON(resolve));
}
load(gl, modelSettingPath, callback) {
this.setUpdating(true);
this.setInitialized(false);
this.modelHomeDir = modelSettingPath.substring(0, modelSettingPath.lastIndexOf('/') + 1);
this.modelSetting = new ModelSettingJson();
this.modelSetting.loadModelSetting(modelSettingPath, () => {
this.loadJSON(callback);
});
}
release(gl) {
const pm = Live2DFramework.getPlatformManager();
gl.deleteTexture(pm.texture);
}
preloadMotionGroup(name) {
for (let i = 0; i < this.modelSetting.getMotionNum(name); i++) {
const file = this.modelSetting.getMotionFile(name, i);
this.loadMotion(file, this.modelHomeDir + file, motion => {
motion.setFadeIn(this.modelSetting.getMotionFadeIn(name, i));
motion.setFadeOut(this.modelSetting.getMotionFadeOut(name, i));
});
}
}
update() {
if (this.live2DModel == null) {
logger.error('Failed to update.');
return;
}
const timeMSec = UtSystem.getUserTimeMSec() - this.startTimeMSec;
const timeSec = timeMSec / 1000.0;
const t = timeSec * 2 * Math.PI;
if (this.mainMotionManager.isFinished()) {
this.startRandomMotion(LAppDefine.MOTION_GROUP_IDLE, LAppDefine.PRIORITY_IDLE);
}
this.live2DModel.loadParam();
const update = this.mainMotionManager.updateParam(this.live2DModel);
if (!update) {
if (this.eyeBlink != null) {
this.eyeBlink.updateParam(this.live2DModel);
}
}
this.live2DModel.saveParam();
if (this.expressionManager != null &&
this.expressions != null &&
!this.expressionManager.isFinished()) {
this.expressionManager.updateParam(this.live2DModel);
}
this.live2DModel.addToParamFloat('PARAM_ANGLE_X', this.dragX * 30, 1);
this.live2DModel.addToParamFloat('PARAM_ANGLE_Y', this.dragY * 30, 1);
this.live2DModel.addToParamFloat('PARAM_ANGLE_Z', this.dragX * this.dragY * -30, 1);
this.live2DModel.addToParamFloat('PARAM_BODY_ANGLE_X', this.dragX * 10, 1);
this.live2DModel.addToParamFloat('PARAM_EYE_BALL_X', this.dragX, 1);
this.live2DModel.addToParamFloat('PARAM_EYE_BALL_Y', this.dragY, 1);
this.live2DModel.addToParamFloat('PARAM_ANGLE_X', Number(15 * Math.sin(t / 6.5345)), 0.5);
this.live2DModel.addToParamFloat('PARAM_ANGLE_Y', Number(8 * Math.sin(t / 3.5345)), 0.5);
this.live2DModel.addToParamFloat('PARAM_ANGLE_Z', Number(10 * Math.sin(t / 5.5345)), 0.5);
this.live2DModel.addToParamFloat('PARAM_BODY_ANGLE_X', Number(4 * Math.sin(t / 15.5345)), 0.5);
this.live2DModel.setParamFloat('PARAM_BREATH', Number(0.5 + 0.5 * Math.sin(t / 3.2345)), 1);
if (this.physics != null) {
this.physics.updateParam(this.live2DModel);
}
if (this.lipSync == null) {
this.live2DModel.setParamFloat('PARAM_MOUTH_OPEN_Y', this.lipSyncValue);
}
if (this.pose != null) {
this.pose.updateParam(this.live2DModel);
}
this.live2DModel.update();
}
setRandomExpression() {
const tmp = [];
for (const name in this.expressions) {
tmp.push(name);
}
const no = parseInt(Math.random() * tmp.length);
this.setExpression(tmp[no]);
}
startRandomMotion(name, priority) {
const max = this.modelSetting.getMotionNum(name);
const no = parseInt(Math.random() * max);
this.startMotion(name, no, priority);
}
startMotion(name, no, priority) {
const motionName = this.modelSetting.getMotionFile(name, no);
if (motionName == null || motionName == '') {
return;
}
if (priority == LAppDefine.PRIORITY_FORCE) {
this.mainMotionManager.setReservePriority(priority);
}
else if (!this.mainMotionManager.reserveMotion(priority)) {
logger.trace('Motion is running.');
return;
}
let motion;
if (this.motions[name] == null) {
this.loadMotion(null, this.modelHomeDir + motionName, mtn => {
motion = mtn;
this.setFadeInFadeOut(name, no, priority, motion);
});
}
else {
motion = this.motions[name];
this.setFadeInFadeOut(name, no, priority, motion);
}
}
setFadeInFadeOut(name, no, priority, motion) {
const motionName = this.modelSetting.getMotionFile(name, no);
motion.setFadeIn(this.modelSetting.getMotionFadeIn(name, no));
motion.setFadeOut(this.modelSetting.getMotionFadeOut(name, no));
logger.trace('Start motion : ' + motionName);
if (this.modelSetting.getMotionSound(name, no) == null) {
this.mainMotionManager.startMotionPrio(motion, priority);
}
else {
const soundName = this.modelSetting.getMotionSound(name, no);
const snd = document.createElement('audio');
snd.src = this.modelHomeDir + soundName;
logger.trace('Start sound : ' + soundName);
snd.play();
this.mainMotionManager.startMotionPrio(motion, priority);
}
}
setExpression(name) {
var _b;
const motion = this.expressions[name];
logger.trace('Expression : ' + name);
(_b = this.expressionManager) === null || _b === void 0 ? void 0 : _b.startMotion(motion, false);
}
draw(gl) {
MatrixStack.push();
MatrixStack.multMatrix(this.modelMatrix.getArray());
this.tmpMatrix = MatrixStack.getMatrix();
this.live2DModel.setMatrix(this.tmpMatrix);
this.live2DModel.draw();
MatrixStack.pop();
}
hitTest(id, testX, testY) {
const len = this.modelSetting.getHitAreaNum();
if (len == 0) {
const hitAreasCustom = this.modelSetting.getHitAreaCustom();
if (hitAreasCustom) {
const x = hitAreasCustom[id + '_x'];
const y = hitAreasCustom[id + '_y'];
if (testX > Math.min(...x) && testX < Math.max(...x) &&
testY > Math.min(...y) && testY < Math.max(...y)) {
return true;
}
}
}
for (let i = 0; i < len; i++) {
if (id == this.modelSetting.getHitAreaName(i)) {
const drawID = this.modelSetting.getHitAreaID(i);
return this.hitTestSimple(drawID, testX, testY);
}
}
return false;
}
}
export default LAppModel;
================================================
FILE: build/cubism2/Live2DFramework.d.ts
================================================
export class L2DBaseModel {
live2DModel: any;
modelMatrix: L2DModelMatrix;
eyeBlink: any;
physics: L2DPhysics;
pose: L2DPose;
initialized: boolean;
updating: boolean;
alpha: number;
accAlpha: number;
lipSync: boolean;
lipSyncValue: number;
accelX: number;
accelY: number;
accelZ: number;
dragX: number;
dragY: number;
startTimeMSec: any;
mainMotionManager: L2DMotionManager;
expressionManager: L2DMotionManager;
motions: {};
expressions: {};
isTexLoaded: boolean;
getModelMatrix(): L2DModelMatrix;
setAlpha(a: any): void;
getAlpha(): number;
isInitialized(): boolean;
setInitialized(v: any): void;
isUpdating(): boolean;
setUpdating(v: any): void;
getLive2DModel(): any;
setLipSync(v: any): void;
setLipSyncValue(v: any): void;
setAccel(x: any, y: any, z: any): void;
setDrag(x: any, y: any): void;
getMainMotionManager(): L2DMotionManager;
getExpressionManager(): L2DMotionManager;
loadModelData(path: any, callback: any): void;
loadTexture(no: any, path: any, callback: any): void;
loadMotion(name: any, path: any, callback: any): void;
loadExpression(name: any, path: any, callback: any): void;
loadPose(path: any, callback: any): void;
loadPhysics(path: any): void;
hitTestSimple(drawID: any, testX: any, testY: any): boolean;
}
export class L2DViewMatrix extends L2DMatrix44 {
screenLeft: any;
screenRight: any;
screenTop: any;
screenBottom: any;
maxLeft: any;
maxRight: any;
maxTop: any;
maxBottom: any;
max: number;
min: number;
getMaxScale(): number;
getMinScale(): number;
setMaxScale(v: any): void;
setMinScale(v: any): void;
isMaxScale(): boolean;
isMinScale(): boolean;
adjustTranslate(shiftX: any, shiftY: any): void;
adjustScale(cx: any, cy: any, scale: any): void;
setScreenRect(left: any, right: any, bottom: any, top: any): void;
setMaxScreenRect(left: any, right: any, bottom: any, top: any): void;
getScreenLeft(): any;
getScreenRight(): any;
getScreenBottom(): any;
getScreenTop(): any;
getMaxLeft(): any;
getMaxRight(): any;
getMaxBottom(): any;
getMaxTop(): any;
}
export class L2DEyeBlink {
nextBlinkTime: any;
stateStartTime: any;
blinkIntervalMsec: number;
eyeState: string;
closingMotionMsec: number;
closedMotionMsec: number;
openingMotionMsec: number;
closeIfZero: boolean;
eyeID_L: string;
eyeID_R: string;
calcNextBlink(): any;
setInterval(blinkIntervalMsec: any): void;
setEyeMotion(closingMotionMsec: any, closedMotionMsec: any, openingMotionMsec: any): void;
updateParam(model: any): void;
}
export class Live2DFramework {
static getPlatformManager(): any;
static setPlatformManager(platformManager: any): void;
}
export namespace Live2DFramework {
let platformManager: any;
}
export class L2DMatrix44 {
static mul(a: any, b: any, dst: any): void;
tr: Float32Array;
identity(): void;
getArray(): Float32Array;
getCopyMatrix(): Float32Array;
setMatrix(tr: any): void;
getScaleX(): number;
getScaleY(): number;
transformX(src: any): number;
transformY(src: any): number;
invertTransformX(src: any): number;
invertTransformY(src: any): number;
multTranslate(shiftX: any, shiftY: any): void;
translate(x: any, y: any): void;
translateX(x: any): void;
translateY(y: any): void;
multScale(scaleX: any, scaleY: any): void;
scale(scaleX: any, scaleY: any): void;
}
export class L2DTargetPoint {
EPSILON: number;
faceTargetX: number;
faceTargetY: number;
faceX: number;
faceY: number;
faceVX: number;
faceVY: number;
lastTimeSec: number;
setPoint(x: any, y: any): void;
getX(): number;
getY(): number;
update(): void;
}
export namespace L2DTargetPoint {
let FRAME_RATE: number;
}
declare class L2DModelMatrix extends L2DMatrix44 {
constructor(w: any, h: any);
width: any;
height: any;
setPosition(x: any, y: any): void;
setCenterPosition(x: any, y: any): void;
top(y: any): void;
bottom(y: any): void;
left(x: any): void;
right(x: any): void;
centerX(x: any): void;
centerY(y: any): void;
setX(x: any): void;
setY(y: any): void;
setHeight(h: any): void;
setWidth(w: any): void;
}
declare class L2DPhysics {
static load(buf: any): L2DPhysics;
physicsList: any[];
startTimeMSec: any;
updateParam(model: any): void;
}
declare class L2DPose {
static load(buf: any): L2DPose;
lastTime: number;
lastModel: any;
partsGroups: any[];
updateParam(model: any): void;
initParam(model: any): void;
normalizePartsOpacityGroup(model: any, partsGroup: any, deltaTimeSec: any): void;
copyOpacityOtherParts(model: any, partsGroup: any): void;
}
declare class L2DMotionManager {
currentPriority: any;
reservePriority: any;
super: any;
getCurrentPriority(): any;
getReservePriority(): any;
reserveMotion(priority: any): boolean;
setReservePriority(val: any): void;
updateParam(model: any): any;
startMotionPrio(motion: any, priority: any): any;
}
export {};
================================================
FILE: build/cubism2/Live2DFramework.js
================================================
import logger from '../logger.js';
class L2DBaseModel {
constructor() {
this.live2DModel = null;
this.modelMatrix = null;
this.eyeBlink = null;
this.physics = null;
this.pose = null;
this.initialized = false;
this.updating = false;
this.alpha = 1;
this.accAlpha = 0;
this.lipSync = false;
this.lipSyncValue = 0;
this.accelX = 0;
this.accelY = 0;
this.accelZ = 0;
this.dragX = 0;
this.dragY = 0;
this.startTimeMSec = null;
this.mainMotionManager = new L2DMotionManager();
this.expressionManager = new L2DMotionManager();
this.motions = {};
this.expressions = {};
this.isTexLoaded = false;
}
getModelMatrix() {
return this.modelMatrix;
}
setAlpha(a) {
if (a > 0.999)
a = 1;
if (a < 0.001)
a = 0;
this.alpha = a;
}
getAlpha() {
return this.alpha;
}
isInitialized() {
return this.initialized;
}
setInitialized(v) {
this.initialized = v;
}
isUpdating() {
return this.updating;
}
setUpdating(v) {
this.updating = v;
}
getLive2DModel() {
return this.live2DModel;
}
setLipSync(v) {
this.lipSync = v;
}
setLipSyncValue(v) {
this.lipSyncValue = v;
}
setAccel(x, y, z) {
this.accelX = x;
this.accelY = y;
this.accelZ = z;
}
setDrag(x, y) {
this.dragX = x;
this.dragY = y;
}
getMainMotionManager() {
return this.mainMotionManager;
}
getExpressionManager() {
return this.expressionManager;
}
loadModelData(path, callback) {
const pm = Live2DFramework.getPlatformManager();
logger.info('Load model : ' + path);
pm.loadLive2DModel(path, (l2dModel) => {
this.live2DModel = l2dModel;
this.live2DModel.saveParam();
const _err = Live2D.getError();
if (_err != 0) {
logger.error('Error : Failed to loadModelData().');
return;
}
this.modelMatrix = new L2DModelMatrix(this.live2DModel.getCanvasWidth(), this.live2DModel.getCanvasHeight());
this.modelMatrix.setWidth(2);
this.modelMatrix.setCenterPosition(0, 0);
callback(this.live2DModel);
});
}
loadTexture(no, path, callback) {
texCounter++;
const pm = Live2DFramework.getPlatformManager();
logger.info('Load Texture : ' + path);
pm.loadTexture(this.live2DModel, no, path, () => {
texCounter--;
if (texCounter == 0)
this.isTexLoaded = true;
if (typeof callback == 'function')
callback();
});
}
loadMotion(name, path, callback) {
const pm = Live2DFramework.getPlatformManager();
logger.trace('Load Motion : ' + path);
let motion = null;
pm.loadBytes(path, (buf) => {
motion = Live2DMotion.loadMotion(buf);
if (name != null) {
this.motions[name] = motion;
}
callback(motion);
});
}
loadExpression(name, path, callback) {
const pm = Live2DFramework.getPlatformManager();
logger.trace('Load Expression : ' + path);
pm.loadBytes(path, (buf) => {
if (name != null) {
this.expressions[name] = L2DExpressionMotion.loadJson(buf);
}
if (typeof callback == 'function')
callback();
});
}
loadPose(path, callback) {
const pm = Live2DFramework.getPlatformManager();
logger.trace('Load Pose : ' + path);
try {
pm.loadBytes(path, (buf) => {
this.pose = L2DPose.load(buf);
if (typeof callback == 'function')
callback();
});
}
catch (e) {
logger.warn(e);
}
}
loadPhysics(path) {
const pm = Live2DFramework.getPlatformManager();
logger.trace('Load Physics : ' + path);
try {
pm.loadBytes(path, (buf) => {
this.physics = L2DPhysics.load(buf);
});
}
catch (e) {
logger.warn(e);
}
}
hitTestSimple(drawID, testX, testY) {
const drawIndex = this.live2DModel.getDrawDataIndex(drawID);
if (drawIndex < 0)
return false;
const points = this.live2DModel.getTransformedPoints(drawIndex);
let left = this.live2DModel.getCanvasWidth();
let right = 0;
let top = this.live2DModel.getCanvasHeight();
let bottom = 0;
for (let j = 0; j < points.length; j = j + 2) {
const x = points[j];
const y = points[j + 1];
if (x < left)
left = x;
if (x > right)
right = x;
if (y < top)
top = y;
if (y > bottom)
bottom = y;
}
const tx = this.modelMatrix.invertTransformX(testX);
const ty = this.modelMatrix.invertTransformY(testY);
return left <= tx && tx <= right && top <= ty && ty <= bottom;
}
}
let texCounter = 0;
class L2DExpressionMotion extends AMotion {
constructor() {
super();
this.paramList = [];
}
static loadJson(buf) {
const ret = new L2DExpressionMotion();
const pm = Live2DFramework.getPlatformManager();
const json = pm.jsonParseFromBytes(buf);
ret.setFadeIn(parseInt(json.fade_in) > 0 ? parseInt(json.fade_in) : 1000);
ret.setFadeOut(parseInt(json.fade_out) > 0 ? parseInt(json.fade_out) : 1000);
if (json.params == null) {
return ret;
}
const params = json.params;
const paramNum = params.length;
ret.paramList = [];
for (let i = 0; i < paramNum; i++) {
const param = params[i];
const paramID = param.id.toString();
let value = parseFloat(param.val);
let calcTypeInt = L2DExpressionMotion.TYPE_ADD;
const calc = param.calc != null ? param.calc.toString() : 'add';
if (calc === 'add') {
calcTypeInt = L2DExpressionMotion.TYPE_ADD;
}
else if (calc === 'mult') {
calcTypeInt = L2DExpressionMotion.TYPE_MULT;
}
else if (calc === 'set') {
calcTypeInt = L2DExpressionMotion.TYPE_SET;
}
else {
calcTypeInt = L2DExpressionMotion.TYPE_ADD;
}
if (calcTypeInt == L2DExpressionMotion.TYPE_ADD) {
let defaultValue = param.def == null ? 0 : parseFloat(param.def);
value = value - defaultValue;
}
else if (calcTypeInt == L2DExpressionMotion.TYPE_MULT) {
let defaultValue = param.def == null ? 1 : parseFloat(param.def);
if (defaultValue == 0)
defaultValue = 1;
value = value / defaultValue;
}
const item = new L2DExpressionParam();
item.id = paramID;
item.type = calcTypeInt;
item.value = value;
ret.paramList.push(item);
}
return ret;
}
updateParamExe(model, timeMSec, weight, motionQueueEnt) {
for (let i = this.paramList.length - 1; i >= 0; --i) {
const param = this.paramList[i];
if (param.type == L2DExpressionMotion.TYPE_ADD) {
model.addToParamFloat(param.id, param.value, weight);
}
else if (param.type == L2DExpressionMotion.TYPE_MULT) {
model.multParamFloat(param.id, param.value, weight);
}
else if (param.type == L2DExpressionMotion.TYPE_SET) {
model.setParamFloat(param.id, param.value, weight);
}
}
}
}
L2DExpressionMotion.EXPRESSION_DEFAULT = 'DEFAULT';
L2DExpressionMotion.TYPE_SET = 0;
L2DExpressionMotion.TYPE_ADD = 1;
L2DExpressionMotion.TYPE_MULT = 2;
function L2DExpressionParam() {
this.id = '';
this.type = -1;
this.value = null;
}
class L2DEyeBlink {
constructor() {
this.nextBlinkTime = null;
this.stateStartTime = null;
this.blinkIntervalMsec = null;
this.eyeState = EYE_STATE.STATE_FIRST;
this.blinkIntervalMsec = 4000;
this.closingMotionMsec = 100;
this.closedMotionMsec = 50;
this.openingMotionMsec = 150;
this.closeIfZero = true;
this.eyeID_L = 'PARAM_EYE_L_OPEN';
this.eyeID_R = 'PARAM_EYE_R_OPEN';
}
calcNextBlink() {
const time = UtSystem.getUserTimeMSec();
const r = Math.random();
return time + r * (2 * this.blinkIntervalMsec - 1);
}
setInterval(blinkIntervalMsec) {
this.blinkIntervalMsec = blinkIntervalMsec;
}
setEyeMotion(closingMotionMsec, closedMotionMsec, openingMotionMsec) {
this.closingMotionMsec = closingMotionMsec;
this.closedMotionMsec = closedMotionMsec;
this.openingMotionMsec = openingMotionMsec;
}
updateParam(model) {
const time = UtSystem.getUserTimeMSec();
let eyeParamValue;
let t = 0;
switch (this.eyeState) {
case EYE_STATE.STATE_CLOSING:
t = (time - this.stateStartTime) / this.closingMotionMsec;
if (t >= 1) {
t = 1;
this.eyeState = EYE_STATE.STATE_CLOSED;
this.stateStartTime = time;
}
eyeParamValue = 1 - t;
break;
case EYE_STATE.STATE_CLOSED:
t = (time - this.stateStartTime) / this.closedMotionMsec;
if (t >= 1) {
this.eyeState = EYE_STATE.STATE_OPENING;
this.stateStartTime = time;
}
eyeParamValue = 0;
break;
case EYE_STATE.STATE_OPENING:
t = (time - this.stateStartTime) / this.openingMotionMsec;
if (t >= 1) {
t = 1;
this.eyeState = EYE_STATE.STATE_INTERVAL;
this.nextBlinkTime = this.calcNextBlink();
}
eyeParamValue = t;
break;
case EYE_STATE.STATE_INTERVAL:
if (this.nextBlinkTime < time) {
this.eyeState = EYE_STATE.STATE_CLOSING;
this.stateStartTime = time;
}
eyeParamValue = 1;
break;
case EYE_STATE.STATE_FIRST:
default:
this.eyeState = EYE_STATE.STATE_INTERVAL;
this.nextBlinkTime = this.calcNextBlink();
eyeParamValue = 1;
break;
}
if (!this.closeIfZero)
eyeParamValue = -eyeParamValue;
model.setParamFloat(this.eyeID_L, eyeParamValue);
model.setParamFloat(this.eyeID_R, eyeParamValue);
}
}
const EYE_STATE = () => { };
EYE_STATE.STATE_FIRST = 'STATE_FIRST';
EYE_STATE.STATE_INTERVAL = 'STATE_INTERVAL';
EYE_STATE.STATE_CLOSING = 'STATE_CLOSING';
EYE_STATE.STATE_CLOSED = 'STATE_CLOSED';
EYE_STATE.STATE_OPENING = 'STATE_OPENING';
class L2DMatrix44 {
constructor() {
this.tr = new Float32Array(16);
this.identity();
}
static mul(a, b, dst) {
const c = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const n = 4;
let i, j, k;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
c[i + j * 4] += a[i + k * 4] * b[k + j * 4];
}
}
}
for (i = 0; i < 16; i++) {
dst[i] = c[i];
}
}
identity() {
for (let i = 0; i < 16; i++)
this.tr[i] = i % 5 == 0 ? 1 : 0;
}
getArray() {
return this.tr;
}
getCopyMatrix() {
return new Float32Array(this.tr);
}
setMatrix(tr) {
if (this.tr == null || this.tr.length != this.tr.length)
return;
for (let i = 0; i < 16; i++)
this.tr[i] = tr[i];
}
getScaleX() {
return this.tr[0];
}
getScaleY() {
return this.tr[5];
}
transformX(src) {
return this.tr[0] * src + this.tr[12];
}
transformY(src) {
return this.tr[5] * src + this.tr[13];
}
invertTransformX(src) {
return (src - this.tr[12]) / this.tr[0];
}
invertTransformY(src) {
return (src - this.tr[13]) / this.tr[5];
}
multTranslate(shiftX, shiftY) {
const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, shiftX, shiftY, 0, 1];
L2DMatrix44.mul(tr1, this.tr, this.tr);
}
translate(x, y) {
this.tr[12] = x;
this.tr[13] = y;
}
translateX(x) {
this.tr[12] = x;
}
translateY(y) {
this.tr[13] = y;
}
multScale(scaleX, scaleY) {
const tr1 = [scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
L2DMatrix44.mul(tr1, this.tr, this.tr);
}
scale(scaleX, scaleY) {
this.tr[0] = scaleX;
this.tr[5] = scaleY;
}
}
class L2DModelMatrix extends L2DMatrix44 {
constructor(w, h) {
super();
this.width = w;
this.height = h;
}
setPosition(x, y) {
this.translate(x, y);
}
setCenterPosition(x, y) {
const w = this.width * this.getScaleX();
const h = this.height * this.getScaleY();
this.translate(x - w / 2, y - h / 2);
}
top(y) {
this.setY(y);
}
bottom(y) {
const h = this.height * this.getScaleY();
this.translateY(y - h);
}
left(x) {
this.setX(x);
}
right(x) {
const w = this.width * this.getScaleX();
this.translateX(x - w);
}
centerX(x) {
const w = this.width * this.getScaleX();
this.translateX(x - w / 2);
}
centerY(y) {
const h = this.height * this.getScaleY();
this.translateY(y - h / 2);
}
setX(x) {
this.translateX(x);
}
setY(y) {
this.translateY(y);
}
setHeight(h) {
const scaleX = h / this.height;
const scaleY = -scaleX;
this.scale(scaleX, scaleY);
}
setWidth(w) {
const scaleX = w / this.width;
const scaleY = -scaleX;
this.scale(scaleX, scaleY);
}
}
class L2DMotionManager extends MotionQueueManager {
constructor() {
super();
this.currentPriority = null;
this.reservePriority = null;
this.super = MotionQueueManager.prototype;
}
getCurrentPriority() {
return this.currentPriority;
}
getReservePriority() {
return this.reservePriority;
}
reserveMotion(priority) {
if (this.reservePriority >= priority) {
return false;
}
if (this.currentPriority >= priority) {
return false;
}
this.reservePriority = priority;
return true;
}
setReservePriority(val) {
this.reservePriority = val;
}
updateParam(model) {
const updated = MotionQueueManager.prototype.updateParam.call(this, model);
if (this.isFinished()) {
this.currentPriority = 0;
}
return updated;
}
startMotionPrio(motion, priority) {
if (priority == this.reservePriority) {
this.reservePriority = 0;
}
this.currentPriority = priority;
return this.startMotion(motion, false);
}
}
class L2DPhysics {
constructor() {
this.physicsList = [];
this.startTimeMSec = UtSystem.getUserTimeMSec();
}
static load(buf) {
const ret = new L2DPhysics();
const pm = Live2DFramework.getPlatformManager();
const json = pm.jsonParseFromBytes(buf);
const params = json.physics_hair;
const paramNum = params.length;
for (let i = 0; i < paramNum; i++) {
const param = params[i];
const physics = new PhysicsHair();
const setup = param.setup;
const length = parseFloat(setup.length);
const resist = parseFloat(setup.regist);
const mass = parseFloat(setup.mass);
physics.setup(length, resist, mass);
const srcList = param.src;
const srcNum = srcList.length;
for (let j = 0; j < srcNum; j++) {
const src = srcList[j];
let id = src.id;
let type = PhysicsHair.Src.SRC_TO_X;
let typeStr = src.ptype;
if (typeStr === 'x') {
type = PhysicsHair.Src.SRC_TO_X;
}
else if (typeStr === 'y') {
type = PhysicsHair.Src.SRC_TO_Y;
}
else if (typeStr === 'angle') {
type = PhysicsHair.Src.SRC_TO_G_ANGLE;
}
else {
UtDebug.error('live2d', 'Invalid parameter:PhysicsHair.Src');
}
let scale = parseFloat(src.scale);
let weight = parseFloat(src.weight);
physics.addSrcParam(type, id, scale, weight);
}
const targetList = param.targets;
const targetNum = targetList.length;
for (let j = 0; j < targetNum; j++) {
const target = targetList[j];
let id = target.id;
let type = PhysicsHair.Target.TARGET_FROM_ANGLE;
let typeStr = target.ptype;
if (typeStr === 'angle') {
type = PhysicsHair.Target.TARGET_FROM_ANGLE;
}
else if (typeStr === 'angle_v') {
type = PhysicsHair.Target.TARGET_FROM_ANGLE_V;
}
else {
UtDebug.error('live2d', 'Invalid parameter:PhysicsHair.Target');
}
let scale = parseFloat(target.scale);
let weight = parseFloat(target.weight);
physics.addTargetParam(type, id, scale, weight);
}
ret.physicsList.push(physics);
}
return ret;
}
updateParam(model) {
const timeMSec = UtSystem.getUserTimeMSec() - this.startTimeMSec;
for (let i = 0; i < this.physicsList.length; i++) {
this.physicsList[i].update(model, timeMSec);
}
}
}
class L2DPose {
constructor() {
this.lastTime = 0;
this.lastModel = null;
this.partsGroups = [];
}
static load(buf) {
const ret = new L2DPose();
const pm = Live2DFramework.getPlatformManager();
const json = pm.jsonParseFromBytes(buf);
const poseListInfo = json.parts_visible;
const poseNum = poseListInfo.length;
for (let i_pose = 0; i_pose < poseNum; i_pose++) {
const poseInfo = poseListInfo[i_pose];
const idListInfo = poseInfo.group;
const idNum = idListInfo.length;
const partsGroup = [];
for (let i_group = 0; i_group < idNum; i_group++) {
const partsInfo = idListInfo[i_group];
const parts = new L2DPartsParam(partsInfo.id);
partsGroup[i_group] = parts;
if (partsInfo.link == null)
continue;
const linkListInfo = partsInfo.link;
const linkNum = linkListInfo.length;
parts.link = [];
for (let i_link = 0; i_link < linkNum; i_link++) {
const linkParts = new L2DPartsParam(linkListInfo[i_link]);
parts.link.push(linkParts);
}
}
ret.partsGroups.push(partsGroup);
}
return ret;
}
updateParam(model) {
if (model == null)
return;
if (!(model == this.lastModel)) {
this.initParam(model);
}
this.lastModel = model;
const curTime = UtSystem.getUserTimeMSec();
let deltaTimeSec = this.lastTime == 0 ? 0 : (curTime - this.lastTime) / 1000.0;
this.lastTime = curTime;
if (deltaTimeSec < 0)
deltaTimeSec = 0;
for (let i = 0; i < this.partsGroups.length; i++) {
this.normalizePartsOpacityGroup(model, this.partsGroups[i], deltaTimeSec);
this.copyOpacityOtherParts(model, this.partsGroups[i]);
}
}
initParam(model) {
if (model == null)
return;
for (let i = 0; i < this.partsGroups.length; i++) {
const partsGroup = this.partsGroups[i];
for (let j = 0; j < partsGroup.length; j++) {
partsGroup[j].initIndex(model);
const partsIndex = partsGroup[j].partsIndex;
const paramIndex = partsGroup[j].paramIndex;
if (partsIndex < 0)
continue;
const v = model.getParamFloat(paramIndex) != 0;
model.setPartsOpacity(partsIndex, v ? 1.0 : 0.0);
model.setParamFloat(paramIndex, v ? 1.0 : 0.0);
if (partsGroup[j].link == null)
continue;
for (let k = 0; k < partsGroup[j].link.length; k++) {
partsGroup[j].link[k].initIndex(model);
}
}
}
}
normalizePartsOpacityGroup(model, partsGroup, deltaTimeSec) {
let visibleParts = -1;
let visibleOpacity = 1.0;
const CLEAR_TIME_SEC = 0.5;
const phi = 0.5;
const maxBackOpacity = 0.15;
for (let i = 0; i < partsGroup.length; i++) {
let partsIndex = partsGroup[i].partsIndex;
const paramIndex = partsGroup[i].paramIndex;
if (partsIndex < 0)
continue;
if (model.getParamFloat(paramIndex) != 0) {
if (visibleParts >= 0) {
break;
}
visibleParts = i;
visibleOpacity = model.getPartsOpacity(partsIndex);
visibleOpacity += deltaTimeSec / CLEAR_TIME_SEC;
if (visibleOpacity > 1) {
visibleOpacity = 1;
}
}
}
if (visibleParts < 0) {
visibleParts = 0;
visibleOpacity = 1;
}
for (let i = 0; i < partsGroup.length; i++) {
let partsIndex = partsGroup[i].partsIndex;
if (partsIndex < 0)
continue;
if (visibleParts == i) {
model.setPartsOpacity(partsIndex, visibleOpacity);
}
else {
let opacity = model.getPartsOpacity(partsIndex);
let a1;
if (visibleOpacity < phi) {
a1 = (visibleOpacity * (phi - 1)) / phi + 1;
}
else {
a1 = ((1 - visibleOpacity) * phi) / (1 - phi);
}
const backOp = (1 - a1) * (1 - visibleOpacity);
if (backOp > maxBackOpacity) {
a1 = 1 - maxBackOpacity / (1 - visibleOpacity);
}
if (opacity > a1) {
opacity = a1;
}
model.setPartsOpacity(partsIndex, opacity);
}
}
}
copyOpacityOtherParts(model, partsGroup) {
for (let i_group = 0; i_group < partsGroup.length; i_group++) {
const partsParam = partsGroup[i_group];
if (partsParam.link == null)
continue;
if (partsParam.partsIndex < 0)
continue;
const opacity = model.getPartsOpacity(partsParam.partsIndex);
for (let i_link = 0; i_link < partsParam.link.length; i_link++) {
const linkParts = partsParam.link[i_link];
if (linkParts.partsIndex < 0)
continue;
model.setPartsOpacity(linkParts.partsIndex, opacity);
}
}
}
}
class L2DPartsParam {
constructor(id) {
this.paramIndex = -1;
this.partsIndex = -1;
this.link = null;
this.id = id;
}
initIndex(model) {
this.paramIndex = model.getParamIndex('VISIBLE:' + this.id);
this.partsIndex = model.getPartsDataIndex(PartsDataID.getID(this.id));
model.setParamFloat(this.paramIndex, 1);
}
}
class L2DTargetPoint {
constructor() {
this.EPSILON = 0.01;
this.faceTargetX = 0;
this.faceTargetY = 0;
this.faceX = 0;
this.faceY = 0;
this.faceVX = 0;
this.faceVY = 0;
this.lastTimeSec = 0;
}
setPoint(x, y) {
this.faceTargetX = x;
this.faceTargetY = y;
}
getX() {
return this.faceX;
}
getY() {
return this.faceY;
}
update() {
const TIME_TO_MAX_SPEED = 0.15;
const FACE_PARAM_MAX_V = 40.0 / 7.5;
const MAX_V = FACE_PARAM_MAX_V / L2DTargetPoint.FRAME_RATE;
if (this.lastTimeSec == 0) {
this.lastTimeSec = UtSystem.getUserTimeMSec();
return;
}
const curTimeSec = UtSystem.getUserTimeMSec();
const deltaTimeWeight = ((curTimeSec - this.lastTimeSec) * L2DTargetPoint.FRAME_RATE) / 1000.0;
this.lastTimeSec = curTimeSec;
const FRAME_TO_MAX_SPEED = TIME_TO_MAX_SPEED * L2DTargetPoint.FRAME_RATE;
const MAX_A = (deltaTimeWeight * MAX_V) / FRAME_TO_MAX_SPEED;
const dx = this.faceTargetX - this.faceX;
const dy = this.faceTargetY - this.faceY;
if (Math.abs(dx) <= this.EPSILON && Math.abs(dy) <= this.EPSILON)
return;
const d = Math.sqrt(dx * dx + dy * dy);
const vx = (MAX_V * dx) / d;
const vy = (MAX_V * dy) / d;
let ax = vx - this.faceVX;
let ay = vy - this.faceVY;
let a = Math.sqrt(ax * ax + ay * ay);
if (a < -MAX_A || a > MAX_A) {
ax *= MAX_A / a;
ay *= MAX_A / a;
a = MAX_A;
}
this.faceVX += ax;
this.faceVY += ay;
{
const max_v = 0.5 *
(Math.sqrt(MAX_A * MAX_A + 16 * MAX_A * d - 8 * MAX_A * d) - MAX_A);
const cur_v = Math.sqrt(this.faceVX * this.faceVX + this.faceVY * this.faceVY);
if (cur_v > max_v) {
this.faceVX *= max_v / cur_v;
this.faceVY *= max_v / cur_v;
}
}
this.faceX += this.faceVX;
this.faceY += this.faceVY;
}
}
L2DTargetPoint.FRAME_RATE = 30;
class L2DViewMatrix extends L2DMatrix44 {
constructor() {
super();
this.screenLeft = null;
this.screenRight = null;
this.screenTop = null;
this.screenBottom = null;
this.maxLeft = null;
this.maxRight = null;
this.maxTop = null;
this.maxBottom = null;
this.max = Number.MAX_VALUE;
this.min = 0;
}
getMaxScale() {
return this.max;
}
getMinScale() {
return this.min;
}
setMaxScale(v) {
this.max = v;
}
setMinScale(v) {
this.min = v;
}
isMaxScale() {
return this.getScaleX() == this.max;
}
isMinScale() {
return this.getScaleX() == this.min;
}
adjustTranslate(shiftX, shiftY) {
if (this.tr[0] * this.maxLeft + (this.tr[12] + shiftX) > this.screenLeft)
shiftX = this.screenLeft - this.tr[0] * this.maxLeft - this.tr[12];
if (this.tr[0] * this.maxRight + (this.tr[12] + shiftX) < this.screenRight)
shiftX = this.screenRight - this.tr[0] * this.maxRight - this.tr[12];
if (this.tr[5] * this.maxTop + (this.tr[13] + shiftY) < this.screenTop)
shiftY = this.screenTop - this.tr[5] * this.maxTop - this.tr[13];
if (this.tr[5] * this.maxBottom + (this.tr[13] + shiftY) >
this.screenBottom)
shiftY = this.screenBottom - this.tr[5] * this.maxBottom - this.tr[13];
const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, shiftX, shiftY, 0, 1];
L2DMatrix44.mul(tr1, this.tr, this.tr);
}
adjustScale(cx, cy, scale) {
const targetScale = scale * this.tr[0];
if (targetScale < this.min) {
if (this.tr[0] > 0)
scale = this.min / this.tr[0];
}
else if (targetScale > this.max) {
if (this.tr[0] > 0)
scale = this.max / this.tr[0];
}
const tr1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1];
const tr2 = [scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
const tr3 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -cx, -cy, 0, 1];
L2DMatrix44.mul(tr3, this.tr, this.tr);
L2DMatrix44.mul(tr2, this.tr, this.tr);
L2DMatrix44.mul(tr1, this.tr, this.tr);
}
setScreenRect(left, right, bottom, top) {
this.screenLeft = left;
this.screenRight = right;
this.screenTop = top;
this.screenBottom = bottom;
}
setMaxScreenRect(left, right, bottom, top) {
this.maxLeft = left;
this.maxRight = right;
this.maxTop = top;
this.maxBottom = bottom;
}
getScreenLeft() {
return this.screenLeft;
}
getScreenRight() {
return this.screenRight;
}
getScreenBottom() {
return this.screenBottom;
}
getScreenTop() {
return this.screenTop;
}
getMaxLeft() {
return this.maxLeft;
}
getMaxRight() {
return this.maxRight;
}
getMaxBottom() {
return this.maxBottom;
}
getMaxTop() {
return this.maxTop;
}
}
class Live2DFramework {
static getPlatformManager() {
return Live2DFramework.platformManager;
}
static setPlatformManager(platformManager) {
Live2DFramework.platformManager = platformManager;
}
}
Live2DFramework.platformManager = null;
export { L2DBaseModel, L2DViewMatrix, L2DEyeBlink, Live2DFramework, L2DMatrix44, L2DTargetPoint };
================================================
FILE: build/cubism2/PlatformManager.d.ts
================================================
export default PlatformManager;
declare class PlatformManager {
cache: {};
loadBytes(path: any, callback: any): any;
loadLive2DModel(path: any, callback: any): void;
loadTexture(model: any, no: any, path: any, callback: any): void;
jsonParseFromBytes(buf: any): any;
}
================================================
FILE: build/cubism2/PlatformManager.js
================================================
import logger from '../logger.js';
class PlatformManager {
constructor() {
this.cache = {};
}
loadBytes(path, callback) {
if (path in this.cache) {
return callback(this.cache[path]);
}
fetch(path)
.then(response => response.arrayBuffer())
.then(arrayBuffer => {
this.cache[path] = arrayBuffer;
callback(arrayBuffer);
});
}
loadLive2DModel(path, callback) {
let model = null;
this.loadBytes(path, buf => {
model = Live2DModelWebGL.loadModel(buf);
callback(model);
});
}
loadTexture(model, no, path, callback) {
const loadedImage = new Image();
loadedImage.crossOrigin = 'anonymous';
loadedImage.src = path;
loadedImage.onload = () => {
const canvas = document.getElementById('live2d');
const gl = canvas.getContext('webgl2', { premultipliedAlpha: true, preserveDrawingBuffer: true });
let texture = gl.createTexture();
if (!texture) {
logger.error('Failed to generate gl texture name.');
return -1;
}
if (model.isPremultipliedAlpha() == false) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
}
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, loadedImage);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.generateMipmap(gl.TEXTURE_2D);
model.setTexture(no, texture);
texture = null;
if (typeof callback == 'function')
callback();
};
loadedImage.onerror = () => {
logger.error('Failed to load image : ' + path);
};
}
jsonParseFromBytes(buf) {
let jsonStr;
const bomCode = new Uint8Array(buf, 0, 3);
if (bomCode[0] == 239 && bomCode[1] == 187 && bomCode[2] == 191) {
jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf, 3));
}
else {
jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf));
}
const jsonObj = JSON.parse(jsonStr);
return jsonObj;
}
}
export default PlatformManager;
================================================
FILE: build/cubism2/index.d.ts
================================================
export default Cubism2Model;
declare class Cubism2Model {
live2DMgr: LAppLive2DManager;
isDrawStart: boolean;
gl: any;
canvas: HTMLElement;
dragMgr: L2DTargetPoint;
viewMatrix: L2DViewMatrix;
projMatrix: L2DMatrix44;
deviceToScreen: L2DMatrix44;
oldLen: number;
_boundMouseEvent: any;
_boundTouchEvent: any;
initL2dCanvas(canvasId: any): void;
init(canvasId: any, modelSettingPath: any, modelSetting: any): Promise;
destroy(): void;
_drawFrameId: number;
startDraw(): void;
draw(): void;
changeModel(modelSettingPath: any): Promise;
changeModelWithJSON(modelSettingPath: any, modelSetting: any): Promise;
modelScaling(scale: any): void;
modelTurnHead(event: any): void;
followPointer(event: any): void;
lookFront(): void;
mouseEvent(e: any): void;
touchEvent(e: any): void;
transformViewX(deviceX: any): number;
transformViewY(deviceY: any): number;
transformScreenX(deviceX: any): number;
transformScreenY(deviceY: any): number;
}
import LAppLive2DManager from './LAppLive2DManager.js';
import { L2DTargetPoint } from './Live2DFramework.js';
import { L2DViewMatrix } from './Live2DFramework.js';
import { L2DMatrix44 } from './Live2DFramework.js';
================================================
FILE: build/cubism2/index.js
================================================
import { L2DMatrix44, L2DTargetPoint, L2DViewMatrix } from './Live2DFramework.js';
import LAppDefine from './LAppDefine.js';
import MatrixStack from './utils/MatrixStack.js';
import LAppLive2DManager from './LAppLive2DManager.js';
import logger from '../logger.js';
function normalizePoint(x, y, x0, y0, w, h) {
const dx = x - x0;
const dy = y - y0;
let targetX = 0, targetY = 0;
if (dx >= 0) {
targetX = dx / (w - x0);
}
else {
targetX = dx / x0;
}
if (dy >= 0) {
targetY = dy / (h - y0);
}
else {
targetY = dy / y0;
}
return {
vx: targetX,
vy: -targetY
};
}
class Cubism2Model {
constructor() {
this.live2DMgr = new LAppLive2DManager();
this.isDrawStart = false;
this.gl = null;
this.canvas = null;
this.dragMgr = null;
this.viewMatrix = null;
this.projMatrix = null;
this.deviceToScreen = null;
this.oldLen = 0;
this._boundMouseEvent = this.mouseEvent.bind(this);
this._boundTouchEvent = this.touchEvent.bind(this);
}
initL2dCanvas(canvasId) {
this.canvas = document.getElementById(canvasId);
if (this.canvas.addEventListener) {
this.canvas.addEventListener('mousewheel', this._boundMouseEvent, false);
this.canvas.addEventListener('click', this._boundMouseEvent, false);
document.addEventListener('mousemove', this._boundMouseEvent, false);
document.addEventListener('mouseout', this._boundMouseEvent, false);
this.canvas.addEventListener('contextmenu', this._boundMouseEvent, false);
this.canvas.addEventListener('touchstart', this._boundTouchEvent, false);
this.canvas.addEventListener('touchend', this._boundTouchEvent, false);
this.canvas.addEventListener('touchmove', this._boundTouchEvent, false);
}
}
async init(canvasId, modelSettingPath, modelSetting) {
this.initL2dCanvas(canvasId);
const width = this.canvas.width;
const height = this.canvas.height;
this.dragMgr = new L2DTargetPoint();
const ratio = height / width;
const left = LAppDefine.VIEW_LOGICAL_LEFT;
const right = LAppDefine.VIEW_LOGICAL_RIGHT;
const bottom = -ratio;
const top = ratio;
this.viewMatrix = new L2DViewMatrix();
this.viewMatrix.setScreenRect(left, right, bottom, top);
this.viewMatrix.setMaxScreenRect(LAppDefine.VIEW_LOGICAL_MAX_LEFT, LAppDefine.VIEW_LOGICAL_MAX_RIGHT, LAppDefine.VIEW_LOGICAL_MAX_BOTTOM, LAppDefine.VIEW_LOGICAL_MAX_TOP);
this.viewMatrix.setMaxScale(LAppDefine.VIEW_MAX_SCALE);
this.viewMatrix.setMinScale(LAppDefine.VIEW_MIN_SCALE);
this.projMatrix = new L2DMatrix44();
this.projMatrix.multScale(1, width / height);
this.deviceToScreen = new L2DMatrix44();
this.deviceToScreen.multTranslate(-width / 2.0, -height / 2.0);
this.deviceToScreen.multScale(2 / width, -2 / width);
this.gl = this.canvas.getContext('webgl2', { premultipliedAlpha: true, preserveDrawingBuffer: true });
if (!this.gl) {
logger.error('Failed to create WebGL context.');
return;
}
Live2D.setGL(this.gl);
this.gl.clearColor(0.0, 0.0, 0.0, 0.0);
await this.changeModelWithJSON(modelSettingPath, modelSetting);
this.startDraw();
}
destroy() {
if (this.canvas) {
this.canvas.removeEventListener('mousewheel', this._boundMouseEvent, false);
this.canvas.removeEventListener('click', this._boundMouseEvent, false);
document.removeEventListener('mousemove', this._boundMouseEvent, false);
document.removeEventListener('mouseout', this._boundMouseEvent, false);
this.canvas.removeEventListener('contextmenu', this._boundMouseEvent, false);
this.canvas.removeEventListener('touchstart', this._boundTouchEvent, false);
this.canvas.removeEventListener('touchend', this._boundTouchEvent, false);
this.canvas.removeEventListener('touchmove', this._boundTouchEvent, false);
}
if (this._drawFrameId) {
window.cancelAnimationFrame(this._drawFrameId);
this._drawFrameId = null;
}
this.isDrawStart = false;
if (this.live2DMgr && typeof this.live2DMgr.release === 'function') {
this.live2DMgr.release();
}
if (this.gl) {
}
this.canvas = null;
this.gl = null;
this.dragMgr = null;
this.viewMatrix = null;
this.projMatrix = null;
this.deviceToScreen = null;
}
startDraw() {
if (!this.isDrawStart) {
this.isDrawStart = true;
const tick = () => {
this.draw();
this._drawFrameId = window.requestAnimationFrame(tick, this.canvas);
};
tick();
}
}
draw() {
MatrixStack.reset();
MatrixStack.loadIdentity();
this.dragMgr.update();
this.live2DMgr.setDrag(this.dragMgr.getX(), this.dragMgr.getY());
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
MatrixStack.multMatrix(this.projMatrix.getArray());
MatrixStack.multMatrix(this.viewMatrix.getArray());
MatrixStack.push();
const model = this.live2DMgr.getModel();
if (model == null)
return;
if (model.initialized && !model.updating) {
model.update();
model.draw(this.gl);
}
MatrixStack.pop();
}
async changeModel(modelSettingPath) {
await this.live2DMgr.changeModel(this.gl, modelSettingPath);
}
async changeModelWithJSON(modelSettingPath, modelSetting) {
await this.live2DMgr.changeModelWithJSON(this.gl, modelSettingPath, modelSetting);
}
modelScaling(scale) {
const isMaxScale = this.viewMatrix.isMaxScale();
const isMinScale = this.viewMatrix.isMinScale();
this.viewMatrix.adjustScale(0, 0, scale);
if (!isMaxScale) {
if (this.viewMatrix.isMaxScale()) {
this.live2DMgr.maxScaleEvent();
}
}
if (!isMinScale) {
if (this.viewMatrix.isMinScale()) {
this.live2DMgr.minScaleEvent();
}
}
}
modelTurnHead(event) {
var _b;
const rect = this.canvas.getBoundingClientRect();
const { vx, vy } = normalizePoint(event.clientX, event.clientY, rect.left + rect.width / 2, rect.top + rect.height / 2, window.innerWidth, window.innerHeight);
logger.trace('onMouseDown device( x:' +
event.clientX +
' y:' +
event.clientY +
' ) view( x:' +
vx +
' y:' +
vy +
')');
this.dragMgr.setPoint(vx, vy);
this.live2DMgr.tapEvent(vx, vy);
if ((_b = this.live2DMgr) === null || _b === void 0 ? void 0 : _b.model.hitTest(LAppDefine.HIT_AREA_BODY, vx, vy)) {
window.dispatchEvent(new Event('live2d:tapbody'));
}
}
followPointer(event) {
var _b;
const rect = this.canvas.getBoundingClientRect();
const { vx, vy } = normalizePoint(event.clientX, event.clientY, rect.left + rect.width / 2, rect.top + rect.height / 2, window.innerWidth, window.innerHeight);
logger.trace('onMouseMove device( x:' +
event.clientX +
' y:' +
event.clientY +
' ) view( x:' +
vx +
' y:' +
vy +
')');
this.dragMgr.setPoint(vx, vy);
if ((_b = this.live2DMgr) === null || _b === void 0 ? void 0 : _b.model.hitTest(LAppDefine.HIT_AREA_BODY, vx, vy)) {
window.dispatchEvent(new Event('live2d:hoverbody'));
}
}
lookFront() {
this.dragMgr.setPoint(0, 0);
}
mouseEvent(e) {
e.preventDefault();
if (e.type == 'mousewheel') {
if (e.wheelDelta > 0)
this.modelScaling(1.1);
else
this.modelScaling(0.9);
}
else if (e.type == 'click' || e.type == 'contextmenu') {
this.modelTurnHead(e);
}
else if (e.type == 'mousemove') {
this.followPointer(e);
}
else if (e.type == 'mouseout') {
this.lookFront();
}
}
touchEvent(e) {
e.preventDefault();
const touch = e.touches[0];
if (e.type == 'touchstart') {
if (e.touches.length == 1)
this.modelTurnHead(touch);
}
else if (e.type == 'touchmove') {
this.followPointer(touch);
if (e.touches.length == 2) {
const touch1 = e.touches[0];
const touch2 = e.touches[1];
const len = Math.pow(touch1.pageX - touch2.pageX, 2) +
Math.pow(touch1.pageY - touch2.pageY, 2);
if (this.oldLen - len < 0)
this.modelScaling(1.025);
else
this.modelScaling(0.975);
this.oldLen = len;
}
}
else if (e.type == 'touchend') {
this.lookFront();
}
}
transformViewX(deviceX) {
const screenX = this.deviceToScreen.transformX(deviceX);
return this.viewMatrix.invertTransformX(screenX);
}
transformViewY(deviceY) {
const screenY = this.deviceToScreen.transformY(deviceY);
return this.viewMatrix.invertTransformY(screenY);
}
transformScreenX(deviceX) {
return this.deviceToScreen.transformX(deviceX);
}
transformScreenY(deviceY) {
return this.deviceToScreen.transformY(deviceY);
}
}
export default Cubism2Model;
================================================
FILE: build/cubism2/utils/MatrixStack.d.ts
================================================
export default MatrixStack;
declare class MatrixStack {
static reset(): void;
static loadIdentity(): void;
static push(): void;
static pop(): void;
static getMatrix(): number[];
static multMatrix(matNew: any): void;
}
declare namespace MatrixStack {
let depth: number;
let matrixStack: number[];
let currentMatrix: number[];
let tmp: any[];
}
================================================
FILE: build/cubism2/utils/MatrixStack.js
================================================
class MatrixStack {
static reset() {
this.depth = 0;
}
static loadIdentity() {
for (let i = 0; i < 16; i++) {
this.currentMatrix[i] = i % 5 == 0 ? 1 : 0;
}
}
static push() {
const offset = this.depth * 16;
const nextOffset = (this.depth + 1) * 16;
if (this.matrixStack.length < nextOffset + 16) {
this.matrixStack.length = nextOffset + 16;
}
for (let i = 0; i < 16; i++) {
this.matrixStack[nextOffset + i] = this.currentMatrix[i];
}
this.depth++;
}
static pop() {
this.depth--;
if (this.depth < 0) {
this.depth = 0;
}
const offset = this.depth * 16;
for (let i = 0; i < 16; i++) {
this.currentMatrix[i] = this.matrixStack[offset + i];
}
}
static getMatrix() {
return this.currentMatrix;
}
static multMatrix(matNew) {
let i, j, k;
for (i = 0; i < 16; i++) {
this.tmp[i] = 0;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
for (k = 0; k < 4; k++) {
this.tmp[i + j * 4] +=
this.currentMatrix[i + k * 4] * matNew[k + j * 4];
}
}
}
for (i = 0; i < 16; i++) {
this.currentMatrix[i] = this.tmp[i];
}
}
}
MatrixStack.matrixStack = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
MatrixStack.depth = 0;
MatrixStack.currentMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
MatrixStack.tmp = new Array(16);
export default MatrixStack;
================================================
FILE: build/cubism2/utils/ModelSettingJson.d.ts
================================================
export default ModelSettingJson;
declare class ModelSettingJson {
NAME: string;
ID: string;
MODEL: string;
TEXTURES: string;
HIT_AREAS: string;
HIT_AREAS_CUSTOM: string;
PHYSICS: string;
POSE: string;
EXPRESSIONS: string;
MOTION_GROUPS: string;
SOUND: string;
FADE_IN: string;
FADE_OUT: string;
LAYOUT: string;
INIT_PARAM: string;
INIT_PARTS_VISIBLE: string;
VALUE: string;
FILE: string;
json: {};
loadModelSetting(path: any, callback: any): void;
getTextureFile(n: any): any;
getModelFile(): any;
getTextureNum(): any;
getHitAreaNum(): any;
getHitAreaCustom(): any;
getHitAreaID(n: any): any;
getHitAreaName(n: any): any;
getPhysicsFile(): any;
getPoseFile(): any;
getExpressionNum(): any;
getExpressionFile(n: any): any;
getExpressionName(n: any): any;
getLayout(): any;
getInitParamNum(): any;
getMotionNum(name: any): any;
getMotionFile(name: any, n: any): any;
getMotionSound(name: any, n: any): any;
getMotionFadeIn(name: any, n: any): any;
getMotionFadeOut(name: any, n: any): any;
getInitParamID(n: any): any;
getInitParamValue(n: any): any;
getInitPartsVisibleNum(): any;
getInitPartsVisibleID(n: any): any;
getInitPartsVisibleValue(n: any): any;
}
================================================
FILE: build/cubism2/utils/ModelSettingJson.js
================================================
import { Live2DFramework } from '../Live2DFramework.js';
class ModelSettingJson {
constructor() {
this.NAME = 'name';
this.ID = 'id';
this.MODEL = 'model';
this.TEXTURES = 'textures';
this.HIT_AREAS = 'hit_areas';
this.HIT_AREAS_CUSTOM = 'hit_areas_custom';
this.PHYSICS = 'physics';
this.POSE = 'pose';
this.EXPRESSIONS = 'expressions';
this.MOTION_GROUPS = 'motions';
this.SOUND = 'sound';
this.FADE_IN = 'fade_in';
this.FADE_OUT = 'fade_out';
this.LAYOUT = 'layout';
this.INIT_PARAM = 'init_param';
this.INIT_PARTS_VISIBLE = 'init_parts_visible';
this.VALUE = 'val';
this.FILE = 'file';
this.json = {};
}
loadModelSetting(path, callback) {
const pm = Live2DFramework.getPlatformManager();
pm.loadBytes(path, buf => {
const str = String.fromCharCode.apply(null, new Uint8Array(buf));
this.json = JSON.parse(str);
callback();
});
}
getTextureFile(n) {
if (this.json[this.TEXTURES] == null || this.json[this.TEXTURES][n] == null)
return null;
return this.json[this.TEXTURES][n];
}
getModelFile() {
return this.json[this.MODEL];
}
getTextureNum() {
if (this.json[this.TEXTURES] == null)
return 0;
return this.json[this.TEXTURES].length;
}
getHitAreaNum() {
if (this.json[this.HIT_AREAS] == null)
return 0;
return this.json[this.HIT_AREAS].length;
}
getHitAreaCustom() {
return this.json[this.HIT_AREAS_CUSTOM];
}
getHitAreaID(n) {
if (this.json[this.HIT_AREAS] == null ||
this.json[this.HIT_AREAS][n] == null)
return null;
return this.json[this.HIT_AREAS][n][this.ID];
}
getHitAreaName(n) {
if (this.json[this.HIT_AREAS] == null ||
this.json[this.HIT_AREAS][n] == null)
return null;
return this.json[this.HIT_AREAS][n][this.NAME];
}
getPhysicsFile() {
return this.json[this.PHYSICS];
}
getPoseFile() {
return this.json[this.POSE];
}
getExpressionNum() {
return this.json[this.EXPRESSIONS] == null
? 0
: this.json[this.EXPRESSIONS].length;
}
getExpressionFile(n) {
if (this.json[this.EXPRESSIONS] == null)
return null;
return this.json[this.EXPRESSIONS][n][this.FILE];
}
getExpressionName(n) {
if (this.json[this.EXPRESSIONS] == null)
return null;
return this.json[this.EXPRESSIONS][n][this.NAME];
}
getLayout() {
return this.json[this.LAYOUT];
}
getInitParamNum() {
return this.json[this.INIT_PARAM] == null
? 0
: this.json[this.INIT_PARAM].length;
}
getMotionNum(name) {
if (this.json[this.MOTION_GROUPS] == null ||
this.json[this.MOTION_GROUPS][name] == null)
return 0;
return this.json[this.MOTION_GROUPS][name].length;
}
getMotionFile(name, n) {
if (this.json[this.MOTION_GROUPS] == null ||
this.json[this.MOTION_GROUPS][name] == null ||
this.json[this.MOTION_GROUPS][name][n] == null)
return null;
return this.json[this.MOTION_GROUPS][name][n][this.FILE];
}
getMotionSound(name, n) {
if (this.json[this.MOTION_GROUPS] == null ||
this.json[this.MOTION_GROUPS][name] == null ||
this.json[this.MOTION_GROUPS][name][n] == null ||
this.json[this.MOTION_GROUPS][name][n][this.SOUND] == null)
return null;
return this.json[this.MOTION_GROUPS][name][n][this.SOUND];
}
getMotionFadeIn(name, n) {
if (this.json[this.MOTION_GROUPS] == null ||
this.json[this.MOTION_GROUPS][name] == null ||
this.json[this.MOTION_GROUPS][name][n] == null ||
this.json[this.MOTION_GROUPS][name][n][this.FADE_IN] == null)
return 1000;
return this.json[this.MOTION_GROUPS][name][n][this.FADE_IN];
}
getMotionFadeOut(name, n) {
if (this.json[this.MOTION_GROUPS] == null ||
this.json[this.MOTION_GROUPS][name] == null ||
this.json[this.MOTION_GROUPS][name][n] == null ||
this.json[this.MOTION_GROUPS][name][n][this.FADE_OUT] == null)
return 1000;
return this.json[this.MOTION_GROUPS][name][n][this.FADE_OUT];
}
getInitParamID(n) {
if (this.json[this.INIT_PARAM] == null ||
this.json[this.INIT_PARAM][n] == null)
return null;
return this.json[this.INIT_PARAM][n][this.ID];
}
getInitParamValue(n) {
if (this.json[this.INIT_PARAM] == null ||
this.json[this.INIT_PARAM][n] == null)
return NaN;
return this.json[this.INIT_PARAM][n][this.VALUE];
}
getInitPartsVisibleNum() {
return this.json[this.INIT_PARTS_VISIBLE] == null
? 0
: this.json[this.INIT_PARTS_VISIBLE].length;
}
getInitPartsVisibleID(n) {
if (this.json[this.INIT_PARTS_VISIBLE] == null ||
this.json[this.INIT_PARTS_VISIBLE][n] == null)
return null;
return this.json[this.INIT_PARTS_VISIBLE][n][this.ID];
}
getInitPartsVisibleValue(n) {
if (this.json[this.INIT_PARTS_VISIBLE] == null ||
this.json[this.INIT_PARTS_VISIBLE][n] == null)
return NaN;
return this.json[this.INIT_PARTS_VISIBLE][n][this.VALUE];
}
}
export default ModelSettingJson;
================================================
FILE: build/cubism5/index.d.ts
================================================
export class AppDelegate extends LAppDelegate {
_drawFrameId: number;
stop(): void;
transformOffset(e: any): {
x: number;
y: number;
};
onMouseMove(e: any): void;
onMouseEnd(e: any): void;
onTap(e: any): void;
mouseMoveEventListener: any;
mouseEndedEventListener: any;
tapEventListener: any;
changeModel(modelSettingPath: string): void;
get subdelegates(): import("@framework/type/csmvector.js").csmVector;
}
import { LAppDelegate } from '@demo/lappdelegate.js';
import { LAppSubdelegate } from '@demo/lappsubdelegate.js';
================================================
FILE: build/cubism5/index.js
================================================
import { LAppDelegate } from '@demo/lappdelegate.js';
import { LAppSubdelegate } from '@demo/lappsubdelegate.js';
import * as LAppDefine from '@demo/lappdefine.js';
import { LAppModel } from '@demo/lappmodel.js';
import { LAppPal } from '@demo/lapppal';
import logger from '../logger.js';
LAppPal.printMessage = () => { };
class AppSubdelegate extends LAppSubdelegate {
initialize(canvas) {
if (!this._glManager.initialize(canvas)) {
return false;
}
this._canvas = canvas;
if (LAppDefine.CanvasSize === 'auto') {
this.resizeCanvas();
}
else {
canvas.width = LAppDefine.CanvasSize.width;
canvas.height = LAppDefine.CanvasSize.height;
}
this._textureManager.setGlManager(this._glManager);
const gl = this._glManager.getGl();
if (!this._frameBuffer) {
this._frameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
}
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
this._view.initialize(this);
this._view._gear = {
render: () => { },
isHit: () => { },
release: () => { }
};
this._view._back = {
render: () => { },
release: () => { }
};
this._live2dManager._subdelegate = this;
this._resizeObserver = new window.ResizeObserver((entries, observer) => this.resizeObserverCallback.call(this, entries, observer));
this._resizeObserver.observe(this._canvas);
return true;
}
onResize() {
this.resizeCanvas();
this._view.initialize(this);
}
update() {
if (this._glManager.getGl().isContextLost()) {
return;
}
if (this._needResize) {
this.onResize();
this._needResize = false;
}
const gl = this._glManager.getGl();
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.clearDepth(1.0);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
this._view.render();
}
}
export class AppDelegate extends LAppDelegate {
run() {
const loop = () => {
LAppPal.updateTime();
for (let i = 0; i < this._subdelegates.getSize(); i++) {
this._subdelegates.at(i).update();
}
this._drawFrameId = window.requestAnimationFrame(loop);
};
loop();
}
stop() {
if (this._drawFrameId) {
window.cancelAnimationFrame(this._drawFrameId);
this._drawFrameId = null;
}
}
release() {
this.stop();
this.releaseEventListener();
this._subdelegates.clear();
this._cubismOption = null;
}
transformOffset(e) {
const subdelegate = this._subdelegates.at(0);
const rect = subdelegate.getCanvas().getBoundingClientRect();
const localX = e.pageX - rect.left;
const localY = e.pageY - rect.top;
const posX = localX * window.devicePixelRatio;
const posY = localY * window.devicePixelRatio;
const x = subdelegate._view.transformViewX(posX);
const y = subdelegate._view.transformViewY(posY);
return {
x, y
};
}
onMouseMove(e) {
const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();
const { x, y } = this.transformOffset(e);
const model = lapplive2dmanager._models.at(0);
lapplive2dmanager.onDrag(x, y);
lapplive2dmanager.onTap(x, y);
if (model.hitTest(LAppDefine.HitAreaNameBody, x, y)) {
window.dispatchEvent(new Event('live2d:hoverbody'));
}
}
onMouseEnd(e) {
const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();
const { x, y } = this.transformOffset(e);
lapplive2dmanager.onDrag(0.0, 0.0);
lapplive2dmanager.onTap(x, y);
}
onTap(e) {
const lapplive2dmanager = this._subdelegates.at(0).getLive2DManager();
const { x, y } = this.transformOffset(e);
const model = lapplive2dmanager._models.at(0);
if (model.hitTest(LAppDefine.HitAreaNameBody, x, y)) {
window.dispatchEvent(new Event('live2d:tapbody'));
}
}
initializeEventListener() {
this.mouseMoveEventListener = this.onMouseMove.bind(this);
this.mouseEndedEventListener = this.onMouseEnd.bind(this);
this.tapEventListener = this.onTap.bind(this);
document.addEventListener('mousemove', this.mouseMoveEventListener, {
passive: true
});
document.addEventListener('mouseout', this.mouseEndedEventListener, {
passive: true
});
document.addEventListener('pointerdown', this.tapEventListener, {
passive: true
});
}
releaseEventListener() {
document.removeEventListener('mousemove', this.mouseMoveEventListener, {
passive: true
});
this.mouseMoveEventListener = null;
document.removeEventListener('mouseout', this.mouseEndedEventListener, {
passive: true
});
this.mouseEndedEventListener = null;
document.removeEventListener('pointerdown', this.tapEventListener, {
passive: true
});
}
initializeSubdelegates() {
this._canvases.prepareCapacity(LAppDefine.CanvasNum);
this._subdelegates.prepareCapacity(LAppDefine.CanvasNum);
const canvas = document.getElementById('live2d');
this._canvases.pushBack(canvas);
canvas.style.width = canvas.width;
canvas.style.height = canvas.height;
for (let i = 0; i < this._canvases.getSize(); i++) {
const subdelegate = new AppSubdelegate();
const result = subdelegate.initialize(this._canvases.at(i));
if (!result) {
logger.error('Failed to initialize AppSubdelegate');
return;
}
this._subdelegates.pushBack(subdelegate);
}
for (let i = 0; i < LAppDefine.CanvasNum; i++) {
if (this._subdelegates.at(i).isContextLost()) {
logger.error(`The context for Canvas at index ${i} was lost, possibly because the acquisition limit for WebGLRenderingContext was reached.`);
}
}
}
changeModel(modelSettingPath) {
const segments = modelSettingPath.split('/');
const modelJsonName = segments.pop();
const modelPath = segments.join('/') + '/';
const live2dManager = this._subdelegates.at(0).getLive2DManager();
live2dManager.releaseAllModel();
const instance = new LAppModel();
instance.setSubdelegate(live2dManager._subdelegate);
instance.loadAssets(modelPath, modelJsonName);
live2dManager._models.pushBack(instance);
}
get subdelegates() {
return this._subdelegates;
}
}
================================================
FILE: build/drag.d.ts
================================================
declare function registerDrag(): void;
export default registerDrag;
================================================
FILE: build/drag.js
================================================
function registerDrag() {
const element = document.getElementById('waifu');
if (!element)
return;
let winWidth = window.innerWidth, winHeight = window.innerHeight;
const imgWidth = element.offsetWidth, imgHeight = element.offsetHeight;
element.addEventListener('mousedown', event => {
if (event.button === 2) {
return;
}
const canvas = document.getElementById('live2d');
if (event.target !== canvas)
return;
event.preventDefault();
const _offsetX = event.offsetX, _offsetY = event.offsetY;
document.onmousemove = event => {
const _x = event.clientX, _y = event.clientY;
let _left = _x - _offsetX, _top = _y - _offsetY;
if (_top < 0) {
_top = 0;
}
else if (_top >= winHeight - imgHeight) {
_top = winHeight - imgHeight;
}
if (_left < 0) {
_left = 0;
}
else if (_left >= winWidth - imgWidth) {
_left = winWidth - imgWidth;
}
element.style.top = _top + 'px';
element.style.left = _left + 'px';
};
document.onmouseup = () => {
document.onmousemove = null;
};
});
window.onresize = () => {
winWidth = window.innerWidth;
winHeight = window.innerHeight;
};
}
export default registerDrag;
================================================
FILE: build/icons.d.ts
================================================
declare const fa_comment = "";
declare const fa_paper_plane = "";
declare const fa_street_view = "";
declare const fa_shirt = "";
declare const fa_camera_retro = "";
declare const fa_info_circle = "";
declare const fa_xmark = "";
declare const fa_child = "";
export { fa_comment, fa_paper_plane, fa_street_view, fa_shirt, fa_camera_retro, fa_info_circle, fa_xmark, fa_child };
================================================
FILE: build/icons.js
================================================
const fa_comment = '';
const fa_paper_plane = '';
const fa_street_view = '';
const fa_shirt = '';
const fa_camera_retro = '';
const fa_info_circle = '';
const fa_xmark = '';
const fa_child = '';
export { fa_comment, fa_paper_plane, fa_street_view, fa_shirt, fa_camera_retro, fa_info_circle, fa_xmark, fa_child };
================================================
FILE: build/index.d.ts
================================================
export { default as registerDrag } from './drag.js';
export { default as logger, LogLevel } from './logger.js';
export { default as Cubism2Model } from './cubism2/index.js';
export * from './tools.js';
export * from './message.js';
export * from './model.js';
export * from './utils.js';
export * from './widget.js';
================================================
FILE: build/index.js
================================================
export { default as registerDrag } from './drag.js';
export { default as logger } from './logger.js';
export { default as Cubism2Model } from './cubism2/index.js';
export * from './tools.js';
export * from './message.js';
export * from './model.js';
export * from './utils.js';
export * from './widget.js';
================================================
FILE: build/logger.d.ts
================================================
type LogLevel = 'error' | 'warn' | 'info' | 'trace';
declare class Logger {
private static levelOrder;
private level;
constructor(level?: LogLevel);
setLevel(level: LogLevel | undefined): void;
private shouldLog;
error(message: string, ...args: any[]): void;
warn(message: string, ...args: any[]): void;
info(message: string, ...args: any[]): void;
trace(message: string, ...args: any[]): void;
}
declare const logger: Logger;
export default logger;
export { LogLevel };
================================================
FILE: build/logger.js
================================================
class Logger {
constructor(level = 'info') {
this.level = level;
}
setLevel(level) {
if (!level)
return;
this.level = level;
}
shouldLog(level) {
return Logger.levelOrder[level] <= Logger.levelOrder[this.level];
}
error(message, ...args) {
if (this.shouldLog('error')) {
console.error('[Live2D Widget][ERROR]', message, ...args);
}
}
warn(message, ...args) {
if (this.shouldLog('warn')) {
console.warn('[Live2D Widget][WARN]', message, ...args);
}
}
info(message, ...args) {
if (this.shouldLog('info')) {
console.log('[Live2D Widget][INFO]', message, ...args);
}
}
trace(message, ...args) {
if (this.shouldLog('trace')) {
console.log('[Live2D Widget][TRACE]', message, ...args);
}
}
}
Logger.levelOrder = {
error: 0,
warn: 1,
info: 2,
trace: 3,
};
const logger = new Logger();
export default logger;
================================================
FILE: build/message.d.ts
================================================
type Time = {
hour: string;
text: string;
}[];
declare function showMessage(text: string | string[], timeout: number, priority: number, override?: boolean): void;
declare function welcomeMessage(time: Time, welcomeTemplate?: string, referrerTemplate?: string): string;
declare function i18n(template: string, ...args: string[]): string;
export { showMessage, welcomeMessage, i18n, Time };
================================================
FILE: build/message.js
================================================
import { randomSelection } from './utils.js';
let messageTimer = null;
function showMessage(text, timeout, priority, override = true) {
let currentPriority = parseInt(sessionStorage.getItem('waifu-message-priority'), 10);
if (isNaN(currentPriority)) {
currentPriority = 0;
}
if (!text ||
(override && currentPriority > priority) ||
(!override && currentPriority >= priority))
return;
if (messageTimer) {
clearTimeout(messageTimer);
messageTimer = null;
}
text = randomSelection(text);
sessionStorage.setItem('waifu-message-priority', String(priority));
const tips = document.getElementById('waifu-tips');
tips.innerHTML = text;
tips.classList.add('waifu-tips-active');
messageTimer = setTimeout(() => {
sessionStorage.removeItem('waifu-message-priority');
tips.classList.remove('waifu-tips-active');
}, timeout);
}
function welcomeMessage(time, welcomeTemplate, referrerTemplate) {
if (location.pathname === '/') {
for (const { hour, text } of time) {
const now = new Date(), after = hour.split('-')[0], before = hour.split('-')[1] || after;
if (Number(after) <= now.getHours() &&
now.getHours() <= Number(before)) {
return text;
}
}
}
if (!welcomeTemplate)
return '';
const text = i18n(welcomeTemplate, document.title);
if (document.referrer === '' || !referrerTemplate)
return text;
const referrer = new URL(document.referrer);
if (location.hostname === referrer.hostname)
return text;
return `${i18n(referrerTemplate, referrer.hostname)} ${text}`;
}
function i18n(template, ...args) {
return template.replace(/\$(\d+)/g, (_, idx) => {
var _b;
const i = parseInt(idx, 10) - 1;
return (_b = args[i]) !== null && _b !== void 0 ? _b : '';
});
}
export { showMessage, welcomeMessage, i18n };
================================================
FILE: build/model.d.ts
================================================
import { LogLevel } from './logger.js';
interface ModelList {
name: string;
paths: string[];
message: string;
}
interface Config {
waifuPath: string;
apiPath?: string;
cdnPath?: string;
cubism2Path?: string;
cubism5Path?: string;
modelId?: number;
tools?: string[];
drag?: boolean;
logLevel?: LogLevel;
}
declare class ModelManager {
readonly useCDN: boolean;
private readonly cdnPath;
private readonly cubism2Path;
private readonly cubism5Path;
private _modelId;
private _modelTexturesId;
private modelList;
private cubism2model;
private cubism5model;
private currentModelVersion;
private loading;
private modelJSONCache;
private models;
private constructor();
static initCheck(config: Config, models?: ModelList[]): Promise;
set modelId(modelId: number);
get modelId(): number;
set modelTexturesId(modelTexturesId: number);
get modelTexturesId(): number;
resetCanvas(): void;
fetchWithCache(url: string): Promise;
checkModelVersion(modelSetting: any): 2 | 3;
loadLive2D(modelSettingPath: string, modelSetting: object): Promise;
loadTextureCache(modelName: string): Promise;
loadModel(message: string | string[]): Promise;
loadRandTexture(successMessage?: string | string[], failMessage?: string | string[]): Promise;
loadNextModel(): Promise;
}
export { ModelManager, Config, ModelList };
================================================
FILE: build/model.js
================================================
import { showMessage } from './message.js';
import { loadExternalResource, randomOtherOption } from './utils.js';
import logger from './logger.js';
class ModelManager {
constructor(config, models = []) {
var _b;
this.modelList = null;
let { apiPath, cdnPath } = config;
const { cubism2Path, cubism5Path } = config;
let useCDN = false;
if (typeof cdnPath === 'string') {
if (!cdnPath.endsWith('/'))
cdnPath += '/';
useCDN = true;
}
else if (typeof apiPath === 'string') {
if (!apiPath.endsWith('/'))
apiPath += '/';
cdnPath = apiPath;
useCDN = true;
logger.warn('apiPath option is deprecated. Please use cdnPath instead.');
}
else if (!models.length) {
throw 'Invalid initWidget argument!';
}
let modelId = parseInt(localStorage.getItem('modelId'), 10);
let modelTexturesId = parseInt(localStorage.getItem('modelTexturesId'), 10);
if (isNaN(modelId) || isNaN(modelTexturesId)) {
modelTexturesId = 0;
}
if (isNaN(modelId)) {
modelId = (_b = config.modelId) !== null && _b !== void 0 ? _b : 0;
}
this.useCDN = useCDN;
this.cdnPath = cdnPath || '';
this.cubism2Path = cubism2Path || '';
this.cubism5Path = cubism5Path || '';
this._modelId = modelId;
this._modelTexturesId = modelTexturesId;
this.currentModelVersion = 0;
this.loading = false;
this.modelJSONCache = {};
this.models = models;
}
static async initCheck(config, models = []) {
const model = new ModelManager(config, models);
if (model.useCDN) {
const response = await fetch(`${model.cdnPath}model_list.json`);
model.modelList = await response.json();
if (model.modelId >= model.modelList.models.length) {
model.modelId = 0;
}
const modelName = model.modelList.models[model.modelId];
if (Array.isArray(modelName)) {
if (model.modelTexturesId >= modelName.length) {
model.modelTexturesId = 0;
}
}
else {
const modelSettingPath = `${model.cdnPath}model/${modelName}/index.json`;
const modelSetting = await model.fetchWithCache(modelSettingPath);
const version = model.checkModelVersion(modelSetting);
if (version === 2) {
const textureCache = await model.loadTextureCache(modelName);
if (model.modelTexturesId >= textureCache.length) {
model.modelTexturesId = 0;
}
}
}
}
else {
if (model.modelId >= model.models.length) {
model.modelId = 0;
}
if (model.modelTexturesId >= model.models[model.modelId].paths.length) {
model.modelTexturesId = 0;
}
}
return model;
}
set modelId(modelId) {
this._modelId = modelId;
localStorage.setItem('modelId', modelId.toString());
}
get modelId() {
return this._modelId;
}
set modelTexturesId(modelTexturesId) {
this._modelTexturesId = modelTexturesId;
localStorage.setItem('modelTexturesId', modelTexturesId.toString());
}
get modelTexturesId() {
return this._modelTexturesId;
}
resetCanvas() {
document.getElementById('waifu-canvas').innerHTML = '';
}
async fetchWithCache(url) {
let result;
if (url in this.modelJSONCache) {
result = this.modelJSONCache[url];
}
else {
try {
const response = await fetch(url);
result = await response.json();
}
catch (_b) {
result = null;
}
this.modelJSONCache[url] = result;
}
return result;
}
checkModelVersion(modelSetting) {
if (modelSetting.Version === 3 || modelSetting.FileReferences) {
return 3;
}
return 2;
}
async loadLive2D(modelSettingPath, modelSetting) {
if (this.loading) {
logger.warn('Still loading. Abort.');
return;
}
this.loading = true;
try {
const version = this.checkModelVersion(modelSetting);
if (version === 2) {
if (!this.cubism2model) {
if (!this.cubism2Path) {
logger.error('No cubism2Path set, cannot load Cubism 2 Core.');
return;
}
await loadExternalResource(this.cubism2Path, 'js');
const { default: Cubism2Model } = await import('./cubism2/index.js');
this.cubism2model = new Cubism2Model();
}
if (this.currentModelVersion === 3) {
this.cubism5model.release();
this.resetCanvas();
}
if (this.currentModelVersion === 3 || !this.cubism2model.gl) {
await this.cubism2model.init('live2d', modelSettingPath, modelSetting);
}
else {
await this.cubism2model.changeModelWithJSON(modelSettingPath, modelSetting);
}
}
else {
if (!this.cubism5Path) {
logger.error('No cubism5Path set, cannot load Cubism 5 Core.');
return;
}
await loadExternalResource(this.cubism5Path, 'js');
const { AppDelegate: Cubism5Model } = await import('./cubism5/index.js');
this.cubism5model = new Cubism5Model();
if (this.currentModelVersion === 2) {
this.cubism2model.destroy();
this.resetCanvas();
}
if (this.currentModelVersion === 2 || !this.cubism5model.subdelegates.at(0)) {
this.cubism5model.initialize();
this.cubism5model.changeModel(modelSettingPath);
this.cubism5model.run();
}
else {
this.cubism5model.changeModel(modelSettingPath);
}
}
logger.info(`Model ${modelSettingPath} (Cubism version ${version}) loaded`);
this.currentModelVersion = version;
}
catch (err) {
console.error('loadLive2D failed', err);
}
this.loading = false;
}
async loadTextureCache(modelName) {
const textureCache = await this.fetchWithCache(`${this.cdnPath}model/${modelName}/textures.cache`);
return textureCache || [];
}
async loadModel(message) {
let modelSettingPath, modelSetting;
if (this.useCDN) {
let modelName = this.modelList.models[this.modelId];
if (Array.isArray(modelName)) {
modelName = modelName[this.modelTexturesId];
}
modelSettingPath = `${this.cdnPath}model/${modelName}/index.json`;
modelSetting = await this.fetchWithCache(modelSettingPath);
const version = this.checkModelVersion(modelSetting);
if (version === 2) {
const textureCache = await this.loadTextureCache(modelName);
if (textureCache.length > 0) {
let textures = textureCache[this.modelTexturesId];
if (typeof textures === 'string')
textures = [textures];
modelSetting.textures = textures;
}
}
}
else {
modelSettingPath = this.models[this.modelId].paths[this.modelTexturesId];
modelSetting = await this.fetchWithCache(modelSettingPath);
}
await this.loadLive2D(modelSettingPath, modelSetting);
showMessage(message, 4000, 10);
}
async loadRandTexture(successMessage = '', failMessage = '') {
const { modelId } = this;
let noTextureAvailable = false;
if (this.useCDN) {
const modelName = this.modelList.models[modelId];
if (Array.isArray(modelName)) {
this.modelTexturesId = randomOtherOption(modelName.length, this.modelTexturesId);
}
else {
const modelSettingPath = `${this.cdnPath}model/${modelName}/index.json`;
const modelSetting = await this.fetchWithCache(modelSettingPath);
const version = this.checkModelVersion(modelSetting);
if (version === 2) {
const textureCache = await this.loadTextureCache(modelName);
if (textureCache.length <= 1) {
noTextureAvailable = true;
}
else {
this.modelTexturesId = randomOtherOption(textureCache.length, this.modelTexturesId);
}
}
else {
noTextureAvailable = true;
}
}
}
else {
if (this.models[modelId].paths.length === 1) {
noTextureAvailable = true;
}
else {
this.modelTexturesId = randomOtherOption(this.models[modelId].paths.length, this.modelTexturesId);
}
}
if (noTextureAvailable) {
showMessage(failMessage, 4000, 10);
}
else {
await this.loadModel(successMessage);
}
}
async loadNextModel() {
this.modelTexturesId = 0;
if (this.useCDN) {
this.modelId = (this.modelId + 1) % this.modelList.models.length;
await this.loadModel(this.modelList.messages[this.modelId]);
}
else {
this.modelId = (this.modelId + 1) % this.models.length;
await this.loadModel(this.models[this.modelId].message);
}
}
}
export { ModelManager };
================================================
FILE: build/tools.d.ts
================================================
import type { Config, ModelManager } from './model.js';
import type { Tips } from './widget.js';
interface Tools {
[key: string]: {
icon: string;
callback: (message: any) => void;
};
}
declare class ToolsManager {
tools: Tools;
config: Config;
constructor(model: ModelManager, config: Config, tips: Tips);
registerTools(): void;
}
export { ToolsManager, Tools };
================================================
FILE: build/tools.js
================================================
import { fa_comment, fa_paper_plane, fa_street_view, fa_shirt, fa_camera_retro, fa_info_circle, fa_xmark } from './icons.js';
import { showMessage, i18n } from './message.js';
class ToolsManager {
constructor(model, config, tips) {
this.config = config;
this.tools = {
hitokoto: {
icon: fa_comment,
callback: async () => {
const response = await fetch('https://v1.hitokoto.cn');
const result = await response.json();
const template = tips.message.hitokoto;
const text = i18n(template, result.from, result.creator);
showMessage(result.hitokoto, 6000, 9);
setTimeout(() => {
showMessage(text, 4000, 9);
}, 6000);
}
},
asteroids: {
icon: fa_paper_plane,
callback: () => {
if (window.Asteroids) {
if (!window.ASTEROIDSPLAYERS)
window.ASTEROIDSPLAYERS = [];
window.ASTEROIDSPLAYERS.push(new window.Asteroids());
}
else {
const script = document.createElement('script');
script.src =
'https://fastly.jsdelivr.net/gh/stevenjoezhang/asteroids/asteroids.js';
document.head.appendChild(script);
}
}
},
'switch-model': {
icon: fa_street_view,
callback: () => model.loadNextModel()
},
'switch-texture': {
icon: fa_shirt,
callback: () => {
let successMessage = '', failMessage = '';
if (tips) {
successMessage = tips.message.changeSuccess;
failMessage = tips.message.changeFail;
}
model.loadRandTexture(successMessage, failMessage);
}
},
photo: {
icon: fa_camera_retro,
callback: () => {
const message = tips.message.photo;
showMessage(message, 6000, 9);
const canvas = document.getElementById('live2d');
if (!canvas)
return;
const imageUrl = canvas.toDataURL();
const link = document.createElement('a');
link.style.display = 'none';
link.href = imageUrl;
link.download = 'live2d-photo.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
},
info: {
icon: fa_info_circle,
callback: () => {
open('https://github.com/stevenjoezhang/live2d-widget');
}
},
quit: {
icon: fa_xmark,
callback: () => {
localStorage.setItem('waifu-display', Date.now().toString());
const message = tips.message.goodbye;
showMessage(message, 2000, 11);
const waifu = document.getElementById('waifu');
if (!waifu)
return;
waifu.classList.remove('waifu-active');
setTimeout(() => {
waifu.classList.add('waifu-hidden');
const waifuToggle = document.getElementById('waifu-toggle');
waifuToggle === null || waifuToggle === void 0 ? void 0 : waifuToggle.classList.add('waifu-toggle-active');
}, 3000);
}
}
};
}
registerTools() {
var _b;
if (!Array.isArray(this.config.tools)) {
this.config.tools = Object.keys(this.tools);
}
for (const toolName of this.config.tools) {
if (this.tools[toolName]) {
const { icon, callback } = this.tools[toolName];
const element = document.createElement('span');
element.id = `waifu-tool-${toolName}`;
element.innerHTML = icon;
(_b = document
.getElementById('waifu-tool')) === null || _b === void 0 ? void 0 : _b.insertAdjacentElement('beforeend', element);
element.addEventListener('click', callback);
}
}
}
}
export { ToolsManager };
================================================
FILE: build/utils.d.ts
================================================
declare function randomSelection(obj: string[] | string): string;
declare function randomOtherOption(total: number, excludeIndex: number): number;
declare function loadExternalResource(url: string, type: string): Promise;
export { randomSelection, loadExternalResource, randomOtherOption };
================================================
FILE: build/utils.js
================================================
function randomSelection(obj) {
return Array.isArray(obj) ? obj[Math.floor(Math.random() * obj.length)] : obj;
}
function randomOtherOption(total, excludeIndex) {
const idx = Math.floor(Math.random() * (total - 1));
return idx >= excludeIndex ? idx + 1 : idx;
}
function loadExternalResource(url, type) {
return new Promise((resolve, reject) => {
let tag;
if (type === 'css') {
tag = document.createElement('link');
tag.rel = 'stylesheet';
tag.href = url;
}
else if (type === 'js') {
tag = document.createElement('script');
tag.src = url;
}
if (tag) {
tag.onload = () => resolve(url);
tag.onerror = () => reject(url);
document.head.appendChild(tag);
}
});
}
export { randomSelection, loadExternalResource, randomOtherOption };
================================================
FILE: build/waifu-tips.d.ts
================================================
export {};
================================================
FILE: build/waifu-tips.js
================================================
import { initWidget } from './widget.js';
window.initWidget = initWidget;
================================================
FILE: build/widget.d.ts
================================================
import { Config, ModelList } from './model.js';
import { Time } from './message.js';
interface Tips {
message: {
default: string[];
console: string;
copy: string;
visibilitychange: string;
changeSuccess: string;
changeFail: string;
photo: string;
goodbye: string;
hitokoto: string;
welcome: string;
referrer: string;
hoverBody: string | string[];
tapBody: string | string[];
};
time: Time;
mouseover: {
selector: string;
text: string | string[];
}[];
click: {
selector: string;
text: string | string[];
}[];
seasons: {
date: string;
text: string | string[];
}[];
models: ModelList[];
}
declare function initWidget(config: string | Config): void;
export { initWidget, Tips };
================================================
FILE: build/widget.js
================================================
import { ModelManager } from './model.js';
import { showMessage, welcomeMessage } from './message.js';
import { randomSelection } from './utils.js';
import { ToolsManager } from './tools.js';
import logger from './logger.js';
import registerDrag from './drag.js';
import { fa_child } from './icons.js';
function registerEventListener(tips) {
let userAction = false;
let userActionTimer;
const messageArray = tips.message.default;
tips.seasons.forEach(({ date, text }) => {
const now = new Date(), after = date.split('-')[0], before = date.split('-')[1] || after;
if (Number(after.split('/')[0]) <= now.getMonth() + 1 &&
now.getMonth() + 1 <= Number(before.split('/')[0]) &&
Number(after.split('/')[1]) <= now.getDate() &&
now.getDate() <= Number(before.split('/')[1])) {
text = randomSelection(text);
text = text.replace('{year}', String(now.getFullYear()));
messageArray.push(text);
}
});
let lastHoverElement;
window.addEventListener('mousemove', () => (userAction = true));
window.addEventListener('keydown', () => (userAction = true));
setInterval(() => {
if (userAction) {
userAction = false;
clearInterval(userActionTimer);
userActionTimer = null;
}
else if (!userActionTimer) {
userActionTimer = setInterval(() => {
showMessage(messageArray, 6000, 9);
}, 20000);
}
}, 1000);
window.addEventListener('mouseover', (event) => {
var _b;
for (let { selector, text } of tips.mouseover) {
if (!((_b = event.target) === null || _b === void 0 ? void 0 : _b.closest(selector)))
continue;
if (lastHoverElement === selector)
return;
lastHoverElement = selector;
text = randomSelection(text);
text = text.replace('{text}', event.target.innerText);
showMessage(text, 4000, 8);
return;
}
});
window.addEventListener('click', (event) => {
var _b;
for (let { selector, text } of tips.click) {
if (!((_b = event.target) === null || _b === void 0 ? void 0 : _b.closest(selector)))
continue;
text = randomSelection(text);
text = text.replace('{text}', event.target.innerText);
showMessage(text, 4000, 8);
return;
}
});
window.addEventListener('live2d:hoverbody', () => {
const text = randomSelection(tips.message.hoverBody);
showMessage(text, 4000, 8, false);
});
window.addEventListener('live2d:tapbody', () => {
const text = randomSelection(tips.message.tapBody);
showMessage(text, 4000, 9);
});
const devtools = () => { };
console.log('%c', devtools);
devtools.toString = () => {
showMessage(tips.message.console, 6000, 9);
};
window.addEventListener('copy', () => {
showMessage(tips.message.copy, 6000, 9);
});
window.addEventListener('visibilitychange', () => {
if (!document.hidden)
showMessage(tips.message.visibilitychange, 6000, 9);
});
}
async function loadWidget(config) {
var _b;
localStorage.removeItem('waifu-display');
sessionStorage.removeItem('waifu-message-priority');
document.body.insertAdjacentHTML('beforeend', `
`);
let models = [];
let tips;
if (config.waifuPath) {
const response = await fetch(config.waifuPath);
tips = await response.json();
models = tips.models;
registerEventListener(tips);
showMessage(welcomeMessage(tips.time, tips.message.welcome, tips.message.referrer), 7000, 11);
}
const model = await ModelManager.initCheck(config, models);
await model.loadModel('');
new ToolsManager(model, config, tips).registerTools();
if (config.drag)
registerDrag();
(_b = document.getElementById('waifu')) === null || _b === void 0 ? void 0 : _b.classList.add('waifu-active');
}
function initWidget(config) {
if (typeof config === 'string') {
logger.error('Your config for Live2D initWidget is outdated. Please refer to https://github.com/stevenjoezhang/live2d-widget/blob/master/dist/autoload.js');
return;
}
logger.setLevel(config.logLevel);
document.body.insertAdjacentHTML('beforeend', `