first commit (without theme files)

This commit is contained in:
Alexander Eckart committed 2012-02-19 14:46:36 +01:00
1 parent f1999fba75
commit a33f488949
126 files changed
+91026

No files matched your search

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+177
View File
@@ -0,0 +1,177 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Info>
<Name>Deutsch</Name>
</Info>
<Texts>
<!--General-->
<TR_PROGRAM_NAME>Vocaluxe</TR_PROGRAM_NAME>
<TR_GENERAL_AND>und</TR_GENERAL_AND>
<!--General: Buttons-->
<TR_BUTTON_EXIT>Exit</TR_BUTTON_EXIT>
<TR_BUTTON_SAVE>Speichern</TR_BUTTON_SAVE>
<TR_BUTTON_BACK>Zurück</TR_BUTTON_BACK>
<TR_BUTTON_START>Start</TR_BUTTON_START>
<!--General: Debug-->
<TR_DEBUG_AUDIO_STREAMS>Audio-Streams</TR_DEBUG_AUDIO_STREAMS>
<TR_DEBUG_VIDEO_STREAMS>Video-Streams</TR_DEBUG_VIDEO_STREAMS>
<TR_DEBUG_TEXTURES>Textures</TR_DEBUG_TEXTURES>
<TR_DEBUG_TONE_ABS>ToneAbs</TR_DEBUG_TONE_ABS>
<TR_DEBUG_MAX_VOLUME>Max. Volume</TR_DEBUG_MAX_VOLUME>
<TR_DEBUG_MOUSE>Maus</TR_DEBUG_MOUSE>
<!--General: Game-Modes-->
<TR_GAMEMODE_NORMAL>Normal</TR_GAMEMODE_NORMAL>
<TR_GAMEMODE_DUET>Duett</TR_GAMEMODE_DUET>
<TR_GAMEMODE_MEDLEY>Medley</TR_GAMEMODE_MEDLEY>
<!--General: Ratings-->
<TR_RATING_VOCAL_HERO>Vocal Hero</TR_RATING_VOCAL_HERO>
<TR_RATING_SUPERSTAR>Superstar</TR_RATING_SUPERSTAR>
<TR_RATING_LEAD_SINGER>Hit-Künstler</TR_RATING_LEAD_SINGER>
<TR_RATING_RISING_STAR>Sternchen</TR_RATING_RISING_STAR>
<TR_RATING_HOPEFUL>Fortgeschritten</TR_RATING_HOPEFUL>
<TR_RATING_WANNABE>Möchtegern</TR_RATING_WANNABE>
<TR_RATING_AMATEUR>Amateur</TR_RATING_AMATEUR>
<TR_RATING_TONE_DEAF>Nichtskönner</TR_RATING_TONE_DEAF>
<!--Config-->
<!--Config: Renderer-->
<TR_CONFIG_SOFTWARE>Software</TR_CONFIG_SOFTWARE>
<TR_CONFIG_OPENGL>OpenGL</TR_CONFIG_OPENGL>
<TR_CONFIG_DIRECT3D>Direct3D</TR_CONFIG_DIRECT3D>
<!--Config: Texture-Quality-->
<TR_CONFIG_TEXTURE_LOWEST>Geringste</TR_CONFIG_TEXTURE_LOWEST>
<TR_CONFIG_TEXTURE_LOW>Gering</TR_CONFIG_TEXTURE_LOW>
<TR_CONFIG_TEXTURE_MEDIUM>Mittel</TR_CONFIG_TEXTURE_MEDIUM>
<TR_CONFIG_TEXTURE_HIGH>Hoch</TR_CONFIG_TEXTURE_HIGH>
<TR_CONFIG_TEXTURE_HIGHEST>Höchste</TR_CONFIG_TEXTURE_HIGHEST>
<!--Config: On/Off-->
<TR_CONFIG_OFF>Aus</TR_CONFIG_OFF>
<TR_CONFIG_ON>An</TR_CONFIG_ON>
<!--Config: Debug-Level-->
<TR_CONFIG_ONLY_FPS>Nur FPS</TR_CONFIG_ONLY_FPS>
<TR_CONFIG_LEVEL1>Level 1</TR_CONFIG_LEVEL1>
<TR_CONFIG_LEVEL2>Level 2</TR_CONFIG_LEVEL2>
<TR_CONFIG_LEVEL3>Level 3</TR_CONFIG_LEVEL3>
<TR_CONFIG_LEVEL_MAX>Maximal</TR_CONFIG_LEVEL_MAX>
<!--Config: Song-Menu-Style-->
<TR_CONFIG_LIST>Liste</TR_CONFIG_LIST>
<TR_CONFIG_DREIDEL>Dreidel</TR_CONFIG_DREIDEL>
<TR_CONFIG_TILE_BOARD>TileBoard</TR_CONFIG_TILE_BOARD>
<TR_CONFIG_BOOK>Book</TR_CONFIG_BOOK>
<!--Config: Cover-Loading-->
<TR_CONFIG_COVERLOADING_ONDEMAND>Bei Bedarf</TR_CONFIG_COVERLOADING_ONDEMAND>
<TR_CONFIG_COVERLOADING_ATSTART>Bei Programmstart</TR_CONFIG_COVERLOADING_ATSTART>
<TR_CONFIG_COVERLOADING_DYNAMIC>Dynamisch</TR_CONFIG_COVERLOADING_DYNAMIC>
<!--Config: Song-Sorting-->
<TR_CONFIG_NONE>Keine</TR_CONFIG_NONE>
<TR_CONFIG_RANDOM>Zufällig</TR_CONFIG_RANDOM>
<TR_CONFIG_FOLDER>Ordner</TR_CONFIG_FOLDER>
<TR_CONFIG_ARTIST>Artist</TR_CONFIG_ARTIST>
<TR_CONFIG_ARTIST_LETTER>Artist Buchstabe</TR_CONFIG_ARTIST_LETTER>
<TR_CONFIG_TITLE_LETTER>Titel Buchstabe</TR_CONFIG_TITLE_LETTER>
<TR_CONFIG_EDITION>Edition</TR_CONFIG_EDITION>
<TR_CONFIG_GENRE>Genre</TR_CONFIG_GENRE>
<TR_CONFIG_YEAR>Jahr</TR_CONFIG_YEAR>
<TR_CONFIG_DECADE>Dekade</TR_CONFIG_DECADE>
<TR_CONFIG_LANGUAGE>Sprache</TR_CONFIG_LANGUAGE>
<!--Config: Game-Difficulty-->
<TR_CONFIG_EASY>Einfach</TR_CONFIG_EASY>
<TR_CONFIG_NORMAL>Normal</TR_CONFIG_NORMAL>
<TR_CONFIG_HARD>Schwierig</TR_CONFIG_HARD>
<!--Config: Timer-Mode-->
<TR_CONFIG_TIMERMODE_CURRENT>Aktuell</TR_CONFIG_TIMERMODE_CURRENT>
<TR_CONFIG_TIMERMODE_REMAINING>Verbleibend</TR_CONFIG_TIMERMODE_REMAINING>
<TR_CONFIG_TIMERMODE_TOTAL>Gesamt</TR_CONFIG_TIMERMODE_TOTAL>
<!--Config: Timer-Look-->
<TR_CONFIG_TIMERLOOK_NORMAL>Normal</TR_CONFIG_TIMERLOOK_NORMAL>
<TR_CONFIG_TIMERLOOK_EXPANDED>Erweitert</TR_CONFIG_TIMERLOOK_EXPANDED>
<!--Screens-->
<!--ScreenLoad-->
<TR_SCREENLOAD_LOADING>Laden</TR_SCREENLOAD_LOADING>
<TR_SCREENLOAD_TOTAL>Gesamt</TR_SCREENLOAD_TOTAL>
<TR_SCREENLOAD_SONGS>Lieder</TR_SCREENLOAD_SONGS>
<TR_SCREENLOAD_LOADED>geladen</TR_SCREENLOAD_LOADED>
<!--ScreenMain-->
<TR_SCREENMAIN_MENU>Hauptmenü</TR_SCREENMAIN_MENU>
<TR_SCREENMAIN_BUTTON_SING>Singen</TR_SCREENMAIN_BUTTON_SING>
<TR_SCREENMAIN_BUTTON_OPTIONS>Optionen</TR_SCREENMAIN_BUTTON_OPTIONS>
<TR_SCREENMAIN_BUTTON_PROFILES>Profile</TR_SCREENMAIN_BUTTON_PROFILES>
<!--ScreenNames-->
<TR_SCREENNAMES_MENU>Spielerauswahl</TR_SCREENNAMES_MENU>
<TR_SCREENNAMES_BUTTON_1PLAYER>1 Spieler</TR_SCREENNAMES_BUTTON_1PLAYER>
<TR_SCREENNAMES_BUTTON_2PLAYER>2 Spieler</TR_SCREENNAMES_BUTTON_2PLAYER>
<TR_SCREENNAMES_BUTTON_3PLAYER>3 Spieler</TR_SCREENNAMES_BUTTON_3PLAYER>
<TR_SCREENNAMES_WARNING_SG>Warnung: Dem Spieler %v ist kein Mikrofon zugeordnet!</TR_SCREENNAMES_WARNING_SG>
<TR_SCREENNAMES_WARNING_PL>Warnung: Den Spielern %v sind keine Mikrofone zugeordnet!</TR_SCREENNAMES_WARNING_PL>
<!--ScreenSong-->
<TR_SCREENSONG_MENU>Songauswahl</TR_SCREENSONG_MENU>
<TR_SCREENSONG_SEARCH>Suche:</TR_SCREENSONG_SEARCH>
<TR_SCREENSONG_NOLANGUAGE>Ohne Sprache</TR_SCREENSONG_NOLANGUAGE>
<TR_SCREENSONG_NOYEAR>Ohne Jahr</TR_SCREENSONG_NOYEAR>
<TR_SCREENSONG_NOGENRE>Ohne Genre</TR_SCREENSONG_NOGENRE>
<TR_SCREENSONG_NOEDITION>Ohne Edition</TR_SCREENSONG_NOEDITION>
<TR_SCREENSONG_ALLSONGS>Alle Songs</TR_SCREENSONG_ALLSONGS>
<TR_SCREENSONG_NUMSONGS>(%v Lieder)</TR_SCREENSONG_NUMSONGS>
<TR_SCREENSONG_NUMSONG>(%v Lied)</TR_SCREENSONG_NUMSONG>
<!--ScreenSing-->
<TR_SCREENSING_PAUSE>Pause</TR_SCREENSING_PAUSE>
<TR_SCREENSING_BUTTON_CANCEL>Lied beenden</TR_SCREENSING_BUTTON_CANCEL>
<TR_SCREENSING_BUTTON_CONTINUE>Fortfahren</TR_SCREENSING_BUTTON_CONTINUE>
<!--ScreenScore-->
<TR_SCREENSCORE_SCORES>Auswertung</TR_SCREENSCORE_SCORES>
<TR_SCREENSCORE_RATING>Bewertung</TR_SCREENSCORE_RATING>
<TR_SCREENSCORE_POINTS>Punkte</TR_SCREENSCORE_POINTS>
<TR_SCREENSCORE_GAMEDIFFICULTY>Schwierigkeit</TR_SCREENSCORE_GAMEDIFFICULTY>
<!--ScreenHighscore-->
<TR_SCREENHIGHSCORE_HIGHSCORE>Highscore</TR_SCREENHIGHSCORE_HIGHSCORE>
<!--ScreenProfiles-->
<TR_SCREENPROFILES_PROFILES>Profile</TR_SCREENPROFILES_PROFILES>
<TR_SCREENPROFILES_PLAYERNAME>Spieler-Name</TR_SCREENPROFILES_PLAYERNAME>
<TR_SCREENPROFILES_GAMEDIFFICULTY>Schwierigkeit</TR_SCREENPROFILES_GAMEDIFFICULTY>
<TR_SCREENPROFILES_AVATAR>Avatar</TR_SCREENPROFILES_AVATAR>
<TR_SCREENPROFILES_GUESTPROFILE>Gast-Profil</TR_SCREENPROFILES_GUESTPROFILE>
<TR_SCREENPROFILES_ACTIVE>Aktiv</TR_SCREENPROFILES_ACTIVE>
<TR_SCREENPROFILES_BUTTON_NEW>Neu</TR_SCREENPROFILES_BUTTON_NEW>
<TR_SCREENPROFILES_BUTTON_DELETE>Löschen</TR_SCREENPROFILES_BUTTON_DELETE>
<!--ScreenOptions-->
<TR_SCREENO_OPTIONS>Einstellungen</TR_SCREENO_OPTIONS>
<TR_SCREENO_BUTTON_GAME>Spiel</TR_SCREENO_BUTTON_GAME>
<TR_SCRENNO_BUTTON_SOUND>Sound</TR_SCRENNO_BUTTON_SOUND>
<TR_SCREENO_BUTTON_RECORD>Aufnahme</TR_SCREENO_BUTTON_RECORD>
<TR_SCREENO_BUTTON_VIDEO>Video</TR_SCREENO_BUTTON_VIDEO>
<TR_SCREENO_BUTTON_THEME>Design</TR_SCREENO_BUTTON_THEME>
<!--ScreenOptionsGame-->
<TR_SCREENOGAME_OPTIONS>Spieleinstellungen</TR_SCREENOGAME_OPTIONS>
<TR_SCREENOGAME_LANGUAGE>Sprache</TR_SCREENOGAME_LANGUAGE>
<TR_SCREENOGAME_DEBUGLEVEL>Debug-Level</TR_SCREENOGAME_DEBUGLEVEL>
<TR_SCREENOGAME_SONGMENU>Song-Menü</TR_SCREENOGAME_SONGMENU>
<TR_SCREENOGAME_SONGSORTING>Song-Sortierung</TR_SCREENOGAME_SONGSORTING>
<TR_SCREENOGAME_TABS>Kategorieren anzeigen</TR_SCREENOGAME_TABS>
<TR_SCREENOGAME_DIFFICULTY>Schwierigkeit</TR_SCREENOGAME_DIFFICULTY>
<TR_SCREENOGAME_TIMERMODE>Timer-Modus</TR_SCREENOGAME_TIMERMODE>
<!--ScreenOptionsRecord-->
<TR_SCREENORECORD_OPTIONS>Aufnahmeeinstellungen</TR_SCREENORECORD_OPTIONS>
<TR_SCREENORECORD_DEVICE>Soundkarte</TR_SCREENORECORD_DEVICE>
<TR_SCREENORECORD_INPUT>Eingang</TR_SCREENORECORD_INPUT>
<TR_SCREENORECORD_CHANNEL_1>Kanal 1</TR_SCREENORECORD_CHANNEL_1>
<TR_SCREENORECORD_CHANNEL_2>Kanal 2</TR_SCREENORECORD_CHANNEL_2>
<TR_SCREENORECORD_MIC_DELAY>Mikrofon-Verzögerung</TR_SCREENORECORD_MIC_DELAY>
<TR_SCREENORECORD_MIC_WARNING>Warnung: Momentan sind einem Spieler zwei Mikrofone zugeordnet!</TR_SCREENORECORD_MIC_WARNING>
<TR_SCREENORECORD_BUTTON_DELAYTEST>Verzögerungs-Test</TR_SCREENORECORD_BUTTON_DELAYTEST>
<!--ScreenOptionsSound-->
<TR_SCREENOSOUND_OPTIONS>Soundeinstellungen</TR_SCREENOSOUND_OPTIONS>
<!--ScreenOptionsTheme-->
<TR_SCREENOTHEME_OPTIONS>Designeinstellungen</TR_SCREENOTHEME_OPTIONS>
<TR_SCREENOTHEME_THEME>Design</TR_SCREENOTHEME_THEME>
<TR_SCREENOTHEME_SKIN>Skin</TR_SCREENOTHEME_SKIN>
<TR_SCREENOTHEME_COVERTHEME>Cover-Theme</TR_SCREENOTHEME_COVERTHEME>
<TR_SCREENOTHEME_NOTELINES>Noten-Linien anzeigen</TR_SCREENOTHEME_NOTELINES>
<TR_SCREENOTHEME_TONEHELPER>Ton-Helfer anzeigen</TR_SCREENOTHEME_TONEHELPER>
<TR_SCREENOTHEME_TIMERLOOK>Aussehen des Timers</TR_SCREENOTHEME_TIMERLOOK>
<TR_SCREENOTHEME_COVERLOADING>Cover Ladeverhalten</TR_SCREENOTHEME_COVERLOADING>
<!--ScreenOptionsVideo-->
<TR_SCREENOVIDEO_OPTIONS>Videoeinstellungen</TR_SCREENOVIDEO_OPTIONS>
<TR_SCREENOVIDEO_VIDEOBACKGROUNDS>Video-Hintergründe</TR_SCREENOVIDEO_VIDEOBACKGROUNDS>
<TR_SCREENOVIDEO_VIDEOPREVIEW>Video-Vorschau</TR_SCREENOVIDEO_VIDEOPREVIEW>
<TR_SCREENOVIDEO_VIDEOINSONGS>Videos während des Singens</TR_SCREENOVIDEO_VIDEOINSONGS>
</Texts>
</root>
+177
View File
@@ -0,0 +1,177 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Info>
<Name>English</Name>
</Info>
<Texts>
<!--General-->
<TR_PROGRAM_NAME>Vocaluxe</TR_PROGRAM_NAME>
<TR_GENERAL_AND>and</TR_GENERAL_AND>
<!--General: Buttons-->
<TR_BUTTON_EXIT>Exit</TR_BUTTON_EXIT>
<TR_BUTTON_SAVE>Save</TR_BUTTON_SAVE>
<TR_BUTTON_BACK>Back</TR_BUTTON_BACK>
<TR_BUTTON_START>Start</TR_BUTTON_START>
<!--General: Debug-->
<TR_DEBUG_AUDIO_STREAMS>Audio streams</TR_DEBUG_AUDIO_STREAMS>
<TR_DEBUG_VIDEO_STREAMS>Video streams</TR_DEBUG_VIDEO_STREAMS>
<TR_DEBUG_TEXTURES>Textures</TR_DEBUG_TEXTURES>
<TR_DEBUG_TONE_ABS>ToneAbs</TR_DEBUG_TONE_ABS>
<TR_DEBUG_MAX_VOLUME>Max Volume</TR_DEBUG_MAX_VOLUME>
<TR_DEBUG_MOUSE>Mouse</TR_DEBUG_MOUSE>
<!--General: Game-Modes-->
<TR_GAMEMODE_NORMAL>Normal</TR_GAMEMODE_NORMAL>
<TR_GAMEMODE_DUET>Duet</TR_GAMEMODE_DUET>
<TR_GAMEMODE_MEDLEY>Medley</TR_GAMEMODE_MEDLEY>
<!--General: Ratings-->
<TR_RATING_VOCAL_HERO>Vocal Hero</TR_RATING_VOCAL_HERO>
<TR_RATING_SUPERSTAR>Superstar</TR_RATING_SUPERSTAR>
<TR_RATING_LEAD_SINGER>Lead Singer</TR_RATING_LEAD_SINGER>
<TR_RATING_RISING_STAR>Rising Star</TR_RATING_RISING_STAR>
<TR_RATING_HOPEFUL>Hopeful</TR_RATING_HOPEFUL>
<TR_RATING_WANNABE>Wannabe</TR_RATING_WANNABE>
<TR_RATING_AMATEUR>Amateur</TR_RATING_AMATEUR>
<TR_RATING_TONE_DEAF>Tone Deaf</TR_RATING_TONE_DEAF>
<!--Config-->
<!--Config: Renderer-->
<TR_CONFIG_SOFTWARE>Software</TR_CONFIG_SOFTWARE>
<TR_CONFIG_OPENGL>OpenGL</TR_CONFIG_OPENGL>
<TR_CONFIG_DIRECT3D>Direct3D</TR_CONFIG_DIRECT3D>
<!--Config: Texture-Quality-->
<TR_CONFIG_TEXTURE_LOWEST>Lowest</TR_CONFIG_TEXTURE_LOWEST>
<TR_CONFIG_TEXTURE_LOW>Low</TR_CONFIG_TEXTURE_LOW>
<TR_CONFIG_TEXTURE_MEDIUM>Medium</TR_CONFIG_TEXTURE_MEDIUM>
<TR_CONFIG_TEXTURE_HIGH>High</TR_CONFIG_TEXTURE_HIGH>
<TR_CONFIG_TEXTURE_HIGHEST>Highest</TR_CONFIG_TEXTURE_HIGHEST>
<!--Config: On/Off-->
<TR_CONFIG_OFF>Off</TR_CONFIG_OFF>
<TR_CONFIG_ON>On</TR_CONFIG_ON>
<!--Config: Debug-Level-->
<TR_CONFIG_ONLY_FPS>Only FPS</TR_CONFIG_ONLY_FPS>
<TR_CONFIG_LEVEL1>Level 1</TR_CONFIG_LEVEL1>
<TR_CONFIG_LEVEL2>Level 2</TR_CONFIG_LEVEL2>
<TR_CONFIG_LEVEL3>Level 3</TR_CONFIG_LEVEL3>
<TR_CONFIG_LEVEL_MAX>Max</TR_CONFIG_LEVEL_MAX>
<!--Config: Song-Menu-Style-->
<TR_CONFIG_LIST>List</TR_CONFIG_LIST>
<TR_CONFIG_DREIDEL>Dreidel</TR_CONFIG_DREIDEL>
<TR_CONFIG_TILE_BOARD>TileBoard</TR_CONFIG_TILE_BOARD>
<TR_CONFIG_BOOK>Book</TR_CONFIG_BOOK>
<!--Config: Cover-Loading-->
<TR_CONFIG_COVERLOADING_ONDEMAND>On Demand</TR_CONFIG_COVERLOADING_ONDEMAND>
<TR_CONFIG_COVERLOADING_ATSTART>At Startup</TR_CONFIG_COVERLOADING_ATSTART>
<TR_CONFIG_COVERLOADING_DYNAMIC>Dynamic</TR_CONFIG_COVERLOADING_DYNAMIC>
<!--Config: Song-Sorting-->
<TR_CONFIG_NONE>None</TR_CONFIG_NONE>
<TR_CONFIG_RANDOM>Random</TR_CONFIG_RANDOM>
<TR_CONFIG_FOLDER>Folder</TR_CONFIG_FOLDER>
<TR_CONFIG_ARTIST>Artist</TR_CONFIG_ARTIST>
<TR_CONFIG_ARTIST_LETTER>Artist Letter</TR_CONFIG_ARTIST_LETTER>
<TR_CONFIG_TITLE_LETTER>Title Letter</TR_CONFIG_TITLE_LETTER>
<TR_CONFIG_EDITION>Edition</TR_CONFIG_EDITION>
<TR_CONFIG_GENRE>Genre</TR_CONFIG_GENRE>
<TR_CONFIG_YEAR>Year</TR_CONFIG_YEAR>
<TR_CONFIG_DECADE>Decade</TR_CONFIG_DECADE>
<TR_CONFIG_LANGUAGE>Language</TR_CONFIG_LANGUAGE>
<!--Config: Game-Difficulty-->
<TR_CONFIG_EASY>Easy</TR_CONFIG_EASY>
<TR_CONFIG_NORMAL>Normal</TR_CONFIG_NORMAL>
<TR_CONFIG_HARD>Hard</TR_CONFIG_HARD>
<!--Config: Timer-Mode-->
<TR_CONFIG_TIMERMODE_CURRENT>Current</TR_CONFIG_TIMERMODE_CURRENT>
<TR_CONFIG_TIMERMODE_REMAINING>Remaining</TR_CONFIG_TIMERMODE_REMAINING>
<TR_CONFIG_TIMERMODE_TOTAL>Total</TR_CONFIG_TIMERMODE_TOTAL>
<!--Config: Timer-Look-->
<TR_CONFIG_TIMERLOOK_NORMAL>Normal</TR_CONFIG_TIMERLOOK_NORMAL>
<TR_CONFIG_TIMERLOOK_EXPANDED>Expanded</TR_CONFIG_TIMERLOOK_EXPANDED>
<!--Screens-->
<!--ScreenLoad-->
<TR_SCREENLOAD_LOADING>Loading</TR_SCREENLOAD_LOADING>
<TR_SCREENLOAD_TOTAL>Total</TR_SCREENLOAD_TOTAL>
<TR_SCREENLOAD_SONGS>Songs</TR_SCREENLOAD_SONGS>
<TR_SCREENLOAD_LOADED>loaded</TR_SCREENLOAD_LOADED>
<!--ScreenMain-->
<TR_SCREENMAIN_MENU>Main Menu</TR_SCREENMAIN_MENU>
<TR_SCREENMAIN_BUTTON_SING>Sing</TR_SCREENMAIN_BUTTON_SING>
<TR_SCREENMAIN_BUTTON_OPTIONS>Options</TR_SCREENMAIN_BUTTON_OPTIONS>
<TR_SCREENMAIN_BUTTON_PROFILES>Profiles</TR_SCREENMAIN_BUTTON_PROFILES>
<!--ScreenNames-->
<TR_SCREENNAMES_MENU>Player Selection</TR_SCREENNAMES_MENU>
<TR_SCREENNAMES_BUTTON_1PLAYER>1 Player</TR_SCREENNAMES_BUTTON_1PLAYER>
<TR_SCREENNAMES_BUTTON_2PLAYER>2 Player</TR_SCREENNAMES_BUTTON_2PLAYER>
<TR_SCREENNAMES_BUTTON_3PLAYER>3 Player</TR_SCREENNAMES_BUTTON_3PLAYER>
<TR_SCREENNAMES_WARNING_SG>Warning: There is no mic assigned to player %v!</TR_SCREENNAMES_WARNING_SG>
<TR_SCREENNAMES_WARNING_PL>Warning: There are no mics assigned to players %v!</TR_SCREENNAMES_WARNING_PL>
<!--ScreenSong-->
<TR_SCREENSONG_MENU>Song Selection</TR_SCREENSONG_MENU>
<TR_SCREENSONG_SEARCH>Search:</TR_SCREENSONG_SEARCH>
<TR_SCREENSONG_NOLANGUAGE>No Language</TR_SCREENSONG_NOLANGUAGE>
<TR_SCREENSONG_NOYEAR>No Year</TR_SCREENSONG_NOYEAR>
<TR_SCREENSONG_NOGENRE>No Genre</TR_SCREENSONG_NOGENRE>
<TR_SCREENSONG_NOEDITION>No Edition</TR_SCREENSONG_NOEDITION>
<TR_SCREENSONG_ALLSONGS>All Songs</TR_SCREENSONG_ALLSONGS>
<TR_SCREENSONG_NUMSONGS>(%v Songs)</TR_SCREENSONG_NUMSONGS>
<TR_SCREENSONG_NUMSONG>(%v Song)</TR_SCREENSONG_NUMSONG>
<!--ScreenSing-->
<TR_SCREENSING_PAUSE>Pause</TR_SCREENSING_PAUSE>
<TR_SCREENSING_BUTTON_CANCEL>Stop singing</TR_SCREENSING_BUTTON_CANCEL>
<TR_SCREENSING_BUTTON_CONTINUE>Continue</TR_SCREENSING_BUTTON_CONTINUE>
<!--ScreenScore-->
<TR_SCREENSCORE_SCORES>Scores</TR_SCREENSCORE_SCORES>
<TR_SCREENSCORE_RATING>Rating</TR_SCREENSCORE_RATING>
<TR_SCREENSCORE_POINTS>Points</TR_SCREENSCORE_POINTS>
<TR_SCREENSCORE_GAMEDIFFICULTY>Difficulty</TR_SCREENSCORE_GAMEDIFFICULTY>
<!--ScreenHighscore-->
<TR_SCREENHIGHSCORE_HIGHSCORE>Highscore</TR_SCREENHIGHSCORE_HIGHSCORE>
<!--ScreenProfiles-->
<TR_SCREENPROFILES_PROFILES>Profiles</TR_SCREENPROFILES_PROFILES>
<TR_SCREENPROFILES_PLAYERNAME>Player Name</TR_SCREENPROFILES_PLAYERNAME>
<TR_SCREENPROFILES_GAMEDIFFICULTY>Game Difficulty</TR_SCREENPROFILES_GAMEDIFFICULTY>
<TR_SCREENPROFILES_AVATAR>Avatar</TR_SCREENPROFILES_AVATAR>
<TR_SCREENPROFILES_GUESTPROFILE>Guest Profile</TR_SCREENPROFILES_GUESTPROFILE>
<TR_SCREENPROFILES_ACTIVE>Active</TR_SCREENPROFILES_ACTIVE>
<TR_SCREENPROFILES_BUTTON_NEW>New</TR_SCREENPROFILES_BUTTON_NEW>
<TR_SCREENPROFILES_BUTTON_DELETE>Delete</TR_SCREENPROFILES_BUTTON_DELETE>
<!--ScreenOptions-->
<TR_SCREENO_OPTIONS>Menu Options</TR_SCREENO_OPTIONS>
<TR_SCREENO_BUTTON_GAME>Game</TR_SCREENO_BUTTON_GAME>
<TR_SCRENNO_BUTTON_SOUND>Sound</TR_SCRENNO_BUTTON_SOUND>
<TR_SCREENO_BUTTON_RECORD>Record</TR_SCREENO_BUTTON_RECORD>
<TR_SCREENO_BUTTON_VIDEO>Video</TR_SCREENO_BUTTON_VIDEO>
<TR_SCREENO_BUTTON_THEME>Theme</TR_SCREENO_BUTTON_THEME>
<!--ScreenOptionsGame-->
<TR_SCREENOGAME_OPTIONS>Game Options</TR_SCREENOGAME_OPTIONS>
<TR_SCREENOGAME_LANGUAGE>Language</TR_SCREENOGAME_LANGUAGE>
<TR_SCREENOGAME_DEBUGLEVEL>Debug Level</TR_SCREENOGAME_DEBUGLEVEL>
<TR_SCREENOGAME_SONGMENU>Song Menu</TR_SCREENOGAME_SONGMENU>
<TR_SCREENOGAME_SONGSORTING>Song Sorting</TR_SCREENOGAME_SONGSORTING>
<TR_SCREENOGAME_TABS>Tabs</TR_SCREENOGAME_TABS>
<TR_SCREENOGAME_DIFFICULTY>Game Difficulty</TR_SCREENOGAME_DIFFICULTY>
<TR_SCREENOGAME_TIMERMODE>Timer-Mode</TR_SCREENOGAME_TIMERMODE>
<!--ScreenOptionsRecord-->
<TR_SCREENORECORD_OPTIONS>Record Options</TR_SCREENORECORD_OPTIONS>
<TR_SCREENORECORD_DEVICE>Device</TR_SCREENORECORD_DEVICE>
<TR_SCREENORECORD_INPUT>Input</TR_SCREENORECORD_INPUT>
<TR_SCREENORECORD_CHANNEL_1>Channel 1</TR_SCREENORECORD_CHANNEL_1>
<TR_SCREENORECORD_CHANNEL_2>Channel 2</TR_SCREENORECORD_CHANNEL_2>
<TR_SCREENORECORD_MIC_DELAY>Mic Delay</TR_SCREENORECORD_MIC_DELAY>
<TR_SCREENORECORD_MIC_WARNING>Warning: At least one player is assigned to two mics.</TR_SCREENORECORD_MIC_WARNING>
<TR_SCREENORECORD_BUTTON_DELAYTEST>Delay Test</TR_SCREENORECORD_BUTTON_DELAYTEST>
<!--ScreenOptionsSound-->
<TR_SCREENOSOUND_OPTIONS>Options Sound</TR_SCREENOSOUND_OPTIONS>
<!--ScreenOptionsTheme-->
<TR_SCREENOTHEME_OPTIONS>Theme Options</TR_SCREENOTHEME_OPTIONS>
<TR_SCREENOTHEME_THEME>Theme</TR_SCREENOTHEME_THEME>
<TR_SCREENOTHEME_SKIN>Skin</TR_SCREENOTHEME_SKIN>
<TR_SCREENOTHEME_COVERTHEME>Cover Theme</TR_SCREENOTHEME_COVERTHEME>
<TR_SCREENOTHEME_NOTELINES>Show Note-Lines</TR_SCREENOTHEME_NOTELINES>
<TR_SCREENOTHEME_TONEHELPER>Show Tone-Helper</TR_SCREENOTHEME_TONEHELPER>
<TR_SCREENOTHEME_TIMERLOOK>Timer-Look</TR_SCREENOTHEME_TIMERLOOK>
<TR_SCREENOTHEME_COVERLOADING>Cover Loading Behavior</TR_SCREENOTHEME_COVERLOADING>
<!--ScreenOptionsVideo-->
<TR_SCREENOVIDEO_OPTIONS>Video Options</TR_SCREENOVIDEO_OPTIONS>
<TR_SCREENOVIDEO_VIDEOBACKGROUNDS>Video Backgrounds</TR_SCREENOVIDEO_VIDEOBACKGROUNDS>
<TR_SCREENOVIDEO_VIDEOPREVIEW>Video Preview</TR_SCREENOVIDEO_VIDEOPREVIEW>
<TR_SCREENOVIDEO_VIDEOINSONGS>Videos while singing</TR_SCREENOVIDEO_VIDEOINSONGS>
</Texts>
</root>
+177
View File
@@ -0,0 +1,177 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Info>
<Name>Français</Name>
</Info>
<Texts>
<!--General-->
<TR_PROGRAM_NAME>Vocaluxe</TR_PROGRAM_NAME>
<TR_GENERAL_AND>et</TR_GENERAL_AND>
<!--General: Buttons-->
<TR_BUTTON_EXIT>Quitter</TR_BUTTON_EXIT>
<TR_BUTTON_SAVE>Sauvegarder</TR_BUTTON_SAVE>
<TR_BUTTON_BACK>Retour</TR_BUTTON_BACK>
<TR_BUTTON_START>Démarrer</TR_BUTTON_START>
<!--General: Debug-->
<TR_DEBUG_AUDIO_STREAMS>Flux Audio</TR_DEBUG_AUDIO_STREAMS>
<TR_DEBUG_VIDEO_STREAMS>Flux Vidéo</TR_DEBUG_VIDEO_STREAMS>
<TR_DEBUG_TEXTURES>Textures</TR_DEBUG_TEXTURES>
<TR_DEBUG_TONE_ABS>ToneAbs</TR_DEBUG_TONE_ABS>
<TR_DEBUG_MAX_VOLUME>Volume Max</TR_DEBUG_MAX_VOLUME>
<TR_DEBUG_MOUSE>Souris</TR_DEBUG_MOUSE>
<!--General: Game-Modes-->
<TR_GAMEMODE_NORMAL>Normal</TR_GAMEMODE_NORMAL>
<TR_GAMEMODE_DUET>Duo</TR_GAMEMODE_DUET>
<TR_GAMEMODE_MEDLEY>Medley</TR_GAMEMODE_MEDLEY>
<!--General: Ratings-->
<TR_RATING_VOCAL_HERO>Vocal Hero</TR_RATING_VOCAL_HERO>
<TR_RATING_SUPERSTAR>Superstar</TR_RATING_SUPERSTAR>
<TR_RATING_LEAD_SINGER>Révélation</TR_RATING_LEAD_SINGER>
<TR_RATING_RISING_STAR>Star en herbe</TR_RATING_RISING_STAR>
<TR_RATING_HOPEFUL>Espoir</TR_RATING_HOPEFUL>
<TR_RATING_WANNABE>Aspirant</TR_RATING_WANNABE>
<TR_RATING_AMATEUR>Amateur</TR_RATING_AMATEUR>
<TR_RATING_TONE_DEAF>Casserole</TR_RATING_TONE_DEAF>
<!--Config-->
<!--Config: Renderer-->
<TR_CONFIG_SOFTWARE>Logiciel</TR_CONFIG_SOFTWARE>
<TR_CONFIG_OPENGL>OpenGL</TR_CONFIG_OPENGL>
<TR_CONFIG_DIRECT3D>Direct3D</TR_CONFIG_DIRECT3D>
<!--Config: Texture-Quality-->
<TR_CONFIG_TEXTURE_LOWEST>Minimum</TR_CONFIG_TEXTURE_LOWEST>
<TR_CONFIG_TEXTURE_LOW>Bas</TR_CONFIG_TEXTURE_LOW>
<TR_CONFIG_TEXTURE_MEDIUM>Moyen</TR_CONFIG_TEXTURE_MEDIUM>
<TR_CONFIG_TEXTURE_HIGH>Haut</TR_CONFIG_TEXTURE_HIGH>
<TR_CONFIG_TEXTURE_HIGHEST>Maximum</TR_CONFIG_TEXTURE_HIGHEST>
<!--Config: On/Off-->
<TR_CONFIG_OFF>Off</TR_CONFIG_OFF>
<TR_CONFIG_ON>On</TR_CONFIG_ON>
<!--Config: Debug-Level-->
<TR_CONFIG_ONLY_FPS>Seulement FPS</TR_CONFIG_ONLY_FPS>
<TR_CONFIG_LEVEL1>Niveau 1</TR_CONFIG_LEVEL1>
<TR_CONFIG_LEVEL2>Niveau 2</TR_CONFIG_LEVEL2>
<TR_CONFIG_LEVEL3>Niveau 3</TR_CONFIG_LEVEL3>
<TR_CONFIG_LEVEL_MAX>Max</TR_CONFIG_LEVEL_MAX>
<!--Config: Song-Menu-Style-->
<TR_CONFIG_LIST>Liste</TR_CONFIG_LIST>
<TR_CONFIG_DREIDEL>Caroussel</TR_CONFIG_DREIDEL>
<TR_CONFIG_TILE_BOARD>Pavement</TR_CONFIG_TILE_BOARD>
<TR_CONFIG_BOOK>Livre</TR_CONFIG_BOOK>
<!--Config: Cover-Loading-->
<TR_CONFIG_COVERLOADING_ONDEMAND>A la demande</TR_CONFIG_COVERLOADING_ONDEMAND>
<TR_CONFIG_COVERLOADING_ATSTART>Au démarrage</TR_CONFIG_COVERLOADING_ATSTART>
<TR_CONFIG_COVERLOADING_DYNAMIC>Dynamique</TR_CONFIG_COVERLOADING_DYNAMIC>
<!--Config: Song-Sorting-->
<TR_CONFIG_NONE>Aucun</TR_CONFIG_NONE>
<TR_CONFIG_RANDOM>Aléatoire</TR_CONFIG_RANDOM>
<TR_CONFIG_FOLDER>Dossier</TR_CONFIG_FOLDER>
<TR_CONFIG_ARTIST>Artiste</TR_CONFIG_ARTIST>
<TR_CONFIG_ARTIST_LETTER>Initiale d'Artiste</TR_CONFIG_ARTIST_LETTER>
<TR_CONFIG_TITLE_LETTER>Initiale de Titre</TR_CONFIG_TITLE_LETTER>
<TR_CONFIG_EDITION>Edition</TR_CONFIG_EDITION>
<TR_CONFIG_GENRE>Genre</TR_CONFIG_GENRE>
<TR_CONFIG_YEAR>Année</TR_CONFIG_YEAR>
<TR_CONFIG_DECADE>Décénie</TR_CONFIG_DECADE>
<TR_CONFIG_LANGUAGE>Langue</TR_CONFIG_LANGUAGE>
<!--Config: Game-Difficulty-->
<TR_CONFIG_EASY>Facile</TR_CONFIG_EASY>
<TR_CONFIG_NORMAL>Moyen</TR_CONFIG_NORMAL>
<TR_CONFIG_HARD>Difficile</TR_CONFIG_HARD>
<!--Config: Timer-Mode-->
<TR_CONFIG_TIMERMODE_CURRENT>Actuel</TR_CONFIG_TIMERMODE_CURRENT>
<TR_CONFIG_TIMERMODE_REMAINING>Restant</TR_CONFIG_TIMERMODE_REMAINING>
<TR_CONFIG_TIMERMODE_TOTAL>Total</TR_CONFIG_TIMERMODE_TOTAL>
<!--Config: Timer-Look-->
<TR_CONFIG_TIMERLOOK_NORMAL>Normal</TR_CONFIG_TIMERLOOK_NORMAL>
<TR_CONFIG_TIMERLOOK_EXPANDED>Développé</TR_CONFIG_TIMERLOOK_EXPANDED>
<!--Screens-->
<!--ScreenLoad-->
<TR_SCREENLOAD_LOADING>Chargement</TR_SCREENLOAD_LOADING>
<TR_SCREENLOAD_TOTAL>Total</TR_SCREENLOAD_TOTAL>
<TR_SCREENLOAD_SONGS>Chansons</TR_SCREENLOAD_SONGS>
<TR_SCREENLOAD_LOADED>chargées</TR_SCREENLOAD_LOADED>
<!--ScreenMain-->
<TR_SCREENMAIN_MENU>Menu Principal</TR_SCREENMAIN_MENU>
<TR_SCREENMAIN_BUTTON_SING>Chanter</TR_SCREENMAIN_BUTTON_SING>
<TR_SCREENMAIN_BUTTON_OPTIONS>Options</TR_SCREENMAIN_BUTTON_OPTIONS>
<TR_SCREENMAIN_BUTTON_PROFILES>Profils</TR_SCREENMAIN_BUTTON_PROFILES>
<!--ScreenNames-->
<TR_SCREENNAMES_MENU>Sélection des joueurs</TR_SCREENNAMES_MENU>
<TR_SCREENNAMES_BUTTON_1PLAYER>1 joueur</TR_SCREENNAMES_BUTTON_1PLAYER>
<TR_SCREENNAMES_BUTTON_2PLAYER>2 joueurs</TR_SCREENNAMES_BUTTON_2PLAYER>
<TR_SCREENNAMES_BUTTON_3PLAYER>3 joueurs</TR_SCREENNAMES_BUTTON_3PLAYER>
<TR_SCREENNAMES_WARNING_SG>Attention: Aucun micro n'est assigné au joueur %v!</TR_SCREENNAMES_WARNING_SG>
<TR_SCREENNAMES_WARNING_PL>Attention: Aucun micro n'est assigné aux joueurs %v!</TR_SCREENNAMES_WARNING_PL>
<!--ScreenSong-->
<TR_SCREENSONG_MENU>Choix de la chanson</TR_SCREENSONG_MENU>
<TR_SCREENSONG_SEARCH>Rechercher:</TR_SCREENSONG_SEARCH>
<TR_SCREENSONG_NOLANGUAGE>Pas de Langue</TR_SCREENSONG_NOLANGUAGE>
<TR_SCREENSONG_NOYEAR>Pas d'Année</TR_SCREENSONG_NOYEAR>
<TR_SCREENSONG_NOGENRE>Pas de Genre</TR_SCREENSONG_NOGENRE>
<TR_SCREENSONG_NOEDITION>Pas d'Edition</TR_SCREENSONG_NOEDITION>
<TR_SCREENSONG_ALLSONGS>Toutes les chansons</TR_SCREENSONG_ALLSONGS>
<TR_SCREENSONG_NUMSONGS>(%v Chansons)</TR_SCREENSONG_NUMSONGS>
<TR_SCREENSONG_NUMSONG>(%v Chanson)</TR_SCREENSONG_NUMSONG>
<!--ScreenSing-->
<TR_SCREENSING_PAUSE>Pause</TR_SCREENSING_PAUSE>
<TR_SCREENSING_BUTTON_CANCEL>Arrêter de chanter</TR_SCREENSING_BUTTON_CANCEL>
<TR_SCREENSING_BUTTON_CONTINUE>Continuer</TR_SCREENSING_BUTTON_CONTINUE>
<!--ScreenScore-->
<TR_SCREENSCORE_SCORES>Scores</TR_SCREENSCORE_SCORES>
<TR_SCREENSCORE_RATING>Note</TR_SCREENSCORE_RATING>
<TR_SCREENSCORE_POINTS>Points</TR_SCREENSCORE_POINTS>
<TR_SCREENSCORE_GAMEDIFFICULTY>Difficulté</TR_SCREENSCORE_GAMEDIFFICULTY>
<!--ScreenHighscore-->
<TR_SCREENHIGHSCORE_HIGHSCORE>Meilleurs Scores</TR_SCREENHIGHSCORE_HIGHSCORE>
<!--ScreenProfiles-->
<TR_SCREENPROFILES_PROFILES>Profils</TR_SCREENPROFILES_PROFILES>
<TR_SCREENPROFILES_PLAYERNAME>Nom du Joueur</TR_SCREENPROFILES_PLAYERNAME>
<TR_SCREENPROFILES_GAMEDIFFICULTY>Difficulté du jeu</TR_SCREENPROFILES_GAMEDIFFICULTY>
<TR_SCREENPROFILES_AVATAR>Avatar</TR_SCREENPROFILES_AVATAR>
<TR_SCREENPROFILES_GUESTPROFILE>Profil Invité</TR_SCREENPROFILES_GUESTPROFILE>
<TR_SCREENPROFILES_ACTIVE>Actif</TR_SCREENPROFILES_ACTIVE>
<TR_SCREENPROFILES_BUTTON_NEW>Nouveau</TR_SCREENPROFILES_BUTTON_NEW>
<TR_SCREENPROFILES_BUTTON_DELETE>Supprimer</TR_SCREENPROFILES_BUTTON_DELETE>
<!--ScreenOptions-->
<TR_SCREENO_OPTIONS>Menu des Options</TR_SCREENO_OPTIONS>
<TR_SCREENO_BUTTON_GAME>Jeu</TR_SCREENO_BUTTON_GAME>
<TR_SCRENNO_BUTTON_SOUND>Son</TR_SCRENNO_BUTTON_SOUND>
<TR_SCREENO_BUTTON_RECORD>Enregistrement</TR_SCREENO_BUTTON_RECORD>
<TR_SCREENO_BUTTON_VIDEO>Vidéo</TR_SCREENO_BUTTON_VIDEO>
<TR_SCREENO_BUTTON_THEME>Thème</TR_SCREENO_BUTTON_THEME>
<!--ScreenOptionsGame-->
<TR_SCREENOGAME_OPTIONS>Options du Jeu</TR_SCREENOGAME_OPTIONS>
<TR_SCREENOGAME_LANGUAGE>Langue</TR_SCREENOGAME_LANGUAGE>
<TR_SCREENOGAME_DEBUGLEVEL>Niveau de Débogage</TR_SCREENOGAME_DEBUGLEVEL>
<TR_SCREENOGAME_SONGMENU>Menu des Chansons</TR_SCREENOGAME_SONGMENU>
<TR_SCREENOGAME_SONGSORTING>Classement des Chansons</TR_SCREENOGAME_SONGSORTING>
<TR_SCREENOGAME_TABS>Dossiers</TR_SCREENOGAME_TABS>
<TR_SCREENOGAME_DIFFICULTY>Difficulté du Jeu</TR_SCREENOGAME_DIFFICULTY>
<TR_SCREENOGAME_TIMERMODE>Mode du Minuteur</TR_SCREENOGAME_TIMERMODE>
<!--ScreenOptionsRecord-->
<TR_SCREENORECORD_OPTIONS>Options d'Enregistrement</TR_SCREENORECORD_OPTIONS>
<TR_SCREENORECORD_DEVICE>Appareil</TR_SCREENORECORD_DEVICE>
<TR_SCREENORECORD_INPUT>Entrée</TR_SCREENORECORD_INPUT>
<TR_SCREENORECORD_CHANNEL_1>Canal 1</TR_SCREENORECORD_CHANNEL_1>
<TR_SCREENORECORD_CHANNEL_2>Canal 2</TR_SCREENORECORD_CHANNEL_2>
<TR_SCREENORECORD_MIC_DELAY>Retard du Micro</TR_SCREENORECORD_MIC_DELAY>
<TR_SCREENORECORD_MIC_WARNING>Attention: Au moins un des joueurs est assigné à 2 micros.</TR_SCREENORECORD_MIC_WARNING>
<TR_SCREENORECORD_BUTTON_DELAYTEST>Test du Retard</TR_SCREENORECORD_BUTTON_DELAYTEST>
<!--ScreenOptionsSound-->
<TR_SCREENOSOUND_OPTIONS>Options du Son</TR_SCREENOSOUND_OPTIONS>
<!--ScreenOptionsTheme-->
<TR_SCREENOTHEME_OPTIONS>Options du Thème</TR_SCREENOTHEME_OPTIONS>
<TR_SCREENOTHEME_THEME>Thème</TR_SCREENOTHEME_THEME>
<TR_SCREENOTHEME_SKIN>Environnement graphique</TR_SCREENOTHEME_SKIN>
<TR_SCREENOTHEME_COVERTHEME>Thème des Couvertures</TR_SCREENOTHEME_COVERTHEME>
<TR_SCREENOTHEME_NOTELINES>Afficher les portées</TR_SCREENOTHEME_NOTELINES>
<TR_SCREENOTHEME_TONEHELPER>Afficher l'aide pour la Tonalité</TR_SCREENOTHEME_TONEHELPER>
<TR_SCREENOTHEME_TIMERLOOK>Apparence du Minuteur</TR_SCREENOTHEME_TIMERLOOK>
<TR_SCREENOTHEME_COVERLOADING>Chargement des couvertures</TR_SCREENOTHEME_COVERLOADING>
<!--ScreenOptionsVideo-->
<TR_SCREENOVIDEO_OPTIONS>Options Vidéo</TR_SCREENOVIDEO_OPTIONS>
<TR_SCREENOVIDEO_VIDEOBACKGROUNDS>Vidéo en arrière plan</TR_SCREENOVIDEO_VIDEOBACKGROUNDS>
<TR_SCREENOVIDEO_VIDEOPREVIEW>Prévisualisation des Vidéos</TR_SCREENOVIDEO_VIDEOPREVIEW>
<TR_SCREENOVIDEO_VIDEOINSONGS>Vidéos pendant que l'on chante</TR_SCREENOVIDEO_VIDEOINSONGS>
</Texts>
</root>
+31
View File
@@ -0,0 +1,31 @@
Microsoft Public License (Ms-PL)
This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
BIN
View File
Binary file not shown.
Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
<configuration>
<dllmap os="linux" dll="opengl32.dll" target="libGL.so.1"/>
<dllmap os="linux" dll="glu32.dll" target="libGLU.so.1"/>
<dllmap os="linux" dll="openal32.dll" target="libopenal.so.1"/>
<dllmap os="linux" dll="alut.dll" target="libalut.so.0"/>
<dllmap os="linux" dll="opencl.dll" target="libOpenCL.so"/>
<dllmap os="osx" dll="openal32.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="alut.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="libGLES.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="libGLESv2.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
</configuration>
Binary file not shown.
BIN
View File
Binary file not shown.
+12
View File
@@ -0,0 +1,12 @@
<configuration>
<dllmap os="linux" dll="opengl32.dll" target="libGL.so.1"/>
<dllmap os="linux" dll="glu32.dll" target="libGLU.so.1"/>
<dllmap os="linux" dll="openal32.dll" target="libopenal.so.1"/>
<dllmap os="linux" dll="alut.dll" target="libalut.so.0"/>
<dllmap os="linux" dll="opencl.dll" target="libOpenCL.so"/>
<dllmap os="osx" dll="openal32.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="alut.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="libGLES.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="libGLESv2.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="opencl.dll" target="/System/Library/Frameworks/OpenCL.framework/OpenCL"/>
</configuration>
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
<configuration>
<dllmap os="linux" dll="PortAudio.dll" target="libportaudio.so"/>
</configuration>
Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<Info>
<PlayerName>Guest 1</PlayerName>
<Difficulty>TR_CONFIG_EASY</Difficulty>
<Avatar>Avatar_f.png</Avatar>
<GuestProfile>TR_CONFIG_ON</GuestProfile>
<Active>TR_CONFIG_ON</Active>
</Info>
</root>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<Info>
<PlayerName>Guest 2</PlayerName>
<Difficulty>TR_CONFIG_EASY</Difficulty>
<Avatar>Avatar_f.png</Avatar>
<GuestProfile>TR_CONFIG_ON</GuestProfile>
<Active>TR_CONFIG_ON</Active>
</Info>
</root>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<Info>
<PlayerName>Guest 3</PlayerName>
<Difficulty>TR_CONFIG_EASY</Difficulty>
<Avatar>Avatar_m.png</Avatar>
<GuestProfile>TR_CONFIG_ON</GuestProfile>
<Active>TR_CONFIG_ON</Active>
</Info>
</root>
BIN
View File
Binary file not shown.
+57639
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
@@ -0,0 +1,10 @@
ScreenOptionsTheme
++++++++++
Version 2:
Add:
<SelectSlideCoverLoading>
and some texts and statics for description (Text8 and Static8)
"TR_SCREENOTHEME_COVERLOADING"
++++++++++
@@ -0,0 +1,22 @@
ScreenSing
++++++++++
Version 3:
Add:
<StaticTimeLineExpandedNormal>
and
<StaticTimeLineExpandedHighlighted>
The Textures and Colors are used by the expanded time bar.
++++++++++
Version 2:
Add:
<SColor>
or
<SR>, <SG>, <SB>, <SA>
to Lyric-Elements.
This option set the color of highlighting lyrics.
++++++++++
@@ -0,0 +1,21 @@
Skin System
++++++++++
Version 3:
Added videos:
<IntroIn>
<IntroMid>
<IntroOut>
++++++++++
++++++++++
Version 2:
Changed:
<ColorSheme>
to
<ColorScheme>
++++++++++
@@ -0,0 +1,69 @@
Theme System
++++++++++
Version 4:
Added:
<TextFont>, <TextMaxW>, <TextStyle>
and
<SkinSelected>, <SkinArrowLeftSelected>, <SkinArrowRightSelected>, <SkinHighlighted>
and
<HColor> or <HR>, <HG>, <HB>, <HA>
on SelectSlide-Elements
Added support for Theme-Fonts (optional)
TextFont: Text font name
TextMaxW: Maximum text width for each element
HColor: Highlighted Color (selected but not focused)
++++++++++
Version 3:
Added:
<SongMenuTileBoard>
on SongMenu-Elements
++++++++++
Version 2:
Changed:
<SelectedColor>
to
<SColor>
on Button-Elements.
Changed:
<SelectedColor>
to
<SColor>
on SelectSlide-Elements.
Changed:
<SelectedR>, <SelectedG>, <SelectedB> and <SelectedA>
to
<SR>, <SG>, <SB> and <SA>
on SelectSlide-Elements.
Changed:
<ArrowSelectedColor>
to
<ArrowSColor>
on SelectSlide-Elements.
Changed:
<ArrowSelectedR>, <ArrowSelectedG>, <ArrowSelectedB> and <ArrowSelectedA>
to
<ArrowSR>, <ArrowSG>, <ArrowSB> and <ArrowSA>
on SelectSlide-Elements.
Changed:
<TextSelectedR>, <TextSelectedG>, <TextSelectedB> and <TextSelectedA>
to
<TextSR>, <TextSG>, <TextSB> and <TextSA>
on SelectSlide-Elements.
++++++++++
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
<configuration>
<dllmap os="linux" dll="acinerella.dll" target="libacinerella.so"/>
</configuration>
BIN
View File
Binary file not shown.
Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C# Express 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vocaluxe", "Vocaluxe\Vocaluxe.csproj", "{2A1E0F2D-5392-4BB7-B0A1-A9DFA13E79FF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2A1E0F2D-5392-4BB7-B0A1-A9DFA13E79FF}.Debug|x86.ActiveCfg = Debug|x86
{2A1E0F2D-5392-4BB7-B0A1-A9DFA13E79FF}.Debug|x86.Build.0 = Debug|x86
{2A1E0F2D-5392-4BB7-B0A1-A9DFA13E79FF}.Release|x86.ActiveCfg = Release|x86
{2A1E0F2D-5392-4BB7-B0A1-A9DFA13E79FF}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+898
View File
@@ -0,0 +1,898 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using OpenTK.Platform;
using Vocaluxe.Lib.Sound;
namespace Vocaluxe.Base
{
#region Enums
public enum ERenderer
{
TR_CONFIG_SOFTWARE,
TR_CONFIG_OPENGL,
TR_CONFIG_DIRECT3D
}
public enum EAntiAliasingModes
{
x0 = 0,
x2 = 2,
x4 = 4,
x8 = 8,
x16 = 16,
x32 = 32
}
public enum EColorDeep
{
Bit8 = 8,
Bit16 = 16,
Bit24 = 24,
Bit32 = 32
}
public enum ETextureQuality
{
TR_CONFIG_TEXTURE_LOWEST,
TR_CONFIG_TEXTURE_LOW,
TR_CONFIG_TEXTURE_MEDIUM,
TR_CONFIG_TEXTURE_HIGH,
TR_CONFIG_TEXTURE_HIGHEST
}
public enum EOffOn
{
TR_CONFIG_OFF,
TR_CONFIG_ON
}
public enum EDebugLevel
{
// don't change the order!
TR_CONFIG_OFF, //no debug infos
TR_CONFIG_ONLY_FPS,
TR_CONFIG_LEVEL1,
TR_CONFIG_LEVEL2,
TR_CONFIG_LEVEL3,
TR_CONFIG_LEVEL_MAX //all debug infos
}
public enum EPlaybackLib
{
BASS,
PortAudio,
NAudio,
OpenAL
}
public enum ERecordLib
{
BASS,
PortAudio
}
public enum EVideoDecoder
{
FFmpeg
}
public enum ESongMenu
{
TR_CONFIG_LIST, //a simple list
TR_CONFIG_DREIDEL, //as in ultrastar deluxe
TR_CONFIG_TILE_BOARD, //chessboard like
TR_CONFIG_BOOK //for playlists
}
public enum ESongSorting
{
TR_CONFIG_NONE,
//TR_CONFIG_RANDOM,
TR_CONFIG_FOLDER,
TR_CONFIG_ARTIST,
TR_CONFIG_ARTIST_LETTER,
TR_CONFIG_TITLE_LETTER,
TR_CONFIG_EDITION,
TR_CONFIG_GENRE,
TR_CONFIG_LANGUAGE,
TR_CONFIG_YEAR,
TR_CONFIG_DECADE
}
public enum ECoverLoading
{
TR_CONFIG_COVERLOADING_ONDEMAND,
TR_CONFIG_COVERLOADING_ATSTART,
TR_CONFIG_COVERLOADING_DYNAMIC
}
public enum EGameDifficulty
{
TR_CONFIG_EASY,
TR_CONFIG_NORMAL,
TR_CONFIG_HARD
}
public enum ETimerMode
{
TR_CONFIG_TIMERMODE_CURRENT,
TR_CONFIG_TIMERMODE_REMAINING,
TR_CONFIG_TIMERMODE_TOTAL
}
public enum ETimerLook
{
TR_CONFIG_TIMERLOOK_NORMAL,
TR_CONFIG_TIMERLOOK_EXPANDED
}
#endregion Enums
static class CConfig
{
private static XmlWriterSettings _settings = new XmlWriterSettings();
// Debug
public static EDebugLevel DebugLevel = EDebugLevel.TR_CONFIG_OFF;
// Graphics
public static ERenderer Renderer = ERenderer.TR_CONFIG_OPENGL;
public static ETextureQuality TextureQuality = ETextureQuality.TR_CONFIG_TEXTURE_MEDIUM;
public static float MaxFPS = 60f;
public static int ScreenW = 1024;
public static int ScreenH = 576;
public static EAntiAliasingModes AAMode = EAntiAliasingModes.x0;
public static EColorDeep Colors = EColorDeep.Bit32;
public static EOffOn VSync = EOffOn.TR_CONFIG_ON;
public static EOffOn FullScreen = EOffOn.TR_CONFIG_ON;
public static float FadeTime = 0.4f;
public static int CoverSize = 128;
// Theme
public static string Theme = "Ambient";
public static string Skin = "Blue";
public static string CoverTheme = "Blue";
public static EOffOn DrawNoteLines = EOffOn.TR_CONFIG_ON;
public static EOffOn DrawToneHelper = EOffOn.TR_CONFIG_ON;
public static ETimerLook TimerLook = ETimerLook.TR_CONFIG_TIMERLOOK_EXPANDED;
public static ECoverLoading CoverLoading = ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART;
// Sound
public static EPlaybackLib PlayBackLib = EPlaybackLib.PortAudio;
public static ERecordLib RecordLib = ERecordLib.PortAudio;
public static uint PortAudioBufferSize = 1024;
// Game
public static List<string> SongFolder = new List<string>();
public static ESongMenu SongMenu = ESongMenu.TR_CONFIG_TILE_BOARD;
public static ESongSorting SongSorting = ESongSorting.TR_CONFIG_FOLDER;
public static float ScoreAnimationTime = 10;
public static ETimerMode TimerMode = ETimerMode.TR_CONFIG_TIMERMODE_REMAINING;
public static int NumPlayer = 2;
public static EOffOn Tabs = EOffOn.TR_CONFIG_ON;
public static string Language = "English";
public static EOffOn LyricsOnTop = EOffOn.TR_CONFIG_OFF;
// Video
public static EVideoDecoder VideoDecoder = EVideoDecoder.FFmpeg;
public static EOffOn VideoBackgrounds = EOffOn.TR_CONFIG_ON;
public static EOffOn VideoPreview = EOffOn.TR_CONFIG_ON;
public static EOffOn VideosInSongs = EOffOn.TR_CONFIG_ON;
// Record
public static SMicConfig[] MicConfig;
public static int MicDelay = 200; //[ms]
//Lists to save parameters and values
private static List<string> _Params = new List<string>();
private static List<string> _Values = new List<string>();
//Variables to save old values for commandline-parameters
private static List<string> SongFolderOld = new List<string>();
public static void Init()
{
_settings.Indent = true;
_settings.Encoding = Encoding.UTF8;
_settings.ConformanceLevel = ConformanceLevel.Document;
SongFolder.Add(Path.Combine(Directory.GetCurrentDirectory(), CSettings.sFolderSongs));
MicConfig = new SMicConfig[CSettings.MaxNumPlayer];
// Init config file
if (File.Exists(CSettings.sFileConfig))
{
LoadConfig();
}
else
{
SaveConfig();
}
}
public static bool LoadConfig()
{
#region Inits
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(CSettings.sFileConfig);
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception)
{
CLog.LogError("Error opening Config.xml (FileName: " + CSettings.sFileConfig);
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
#endregion Inits
if (loaded)
{
string value = string.Empty;
#region Debug
CHelper.TryGetEnumValueFromXML<EDebugLevel>("//root/Debug/DebugLevel", navigator, ref DebugLevel);
#endregion Debug
#region Graphics
CHelper.TryGetEnumValueFromXML<ERenderer>("//root/Graphics/Renderer", navigator, ref Renderer);
CHelper.TryGetEnumValueFromXML<ETextureQuality>("//root/Graphics/TextureQuality", navigator, ref TextureQuality);
CHelper.TryGetIntValueFromXML("//root/Graphics/ScreenW", navigator, ref ScreenW);
CHelper.TryGetIntValueFromXML("//root/Graphics/ScreenH", navigator, ref ScreenH);
CHelper.TryGetEnumValueFromXML<EAntiAliasingModes>("//root/Graphics/AAMode", navigator, ref AAMode);
CHelper.TryGetEnumValueFromXML<EColorDeep>("//root/Graphics/Colors", navigator, ref Colors);
CHelper.TryGetFloatValueFromXML("//root/Graphics/MaxFPS", navigator, ref MaxFPS);
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Graphics/VSync", navigator, ref VSync);
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Graphics/FullScreen", navigator, ref FullScreen);
CHelper.TryGetFloatValueFromXML("//root/Graphics/FadeTime", navigator, ref FadeTime);
#endregion Graphics
#region Theme
CHelper.GetValueFromXML("//root/Theme/Name", navigator, ref Theme, Theme);
CHelper.GetValueFromXML("//root/Theme/Skin", navigator, ref Skin, Skin);
CHelper.GetValueFromXML("//root/Theme/Cover", navigator, ref CoverTheme, CoverTheme);
CHelper.TryGetEnumValueFromXML("//root/Theme/DrawNoteLines", navigator, ref DrawNoteLines);
CHelper.TryGetEnumValueFromXML("//root/Theme/DrawToneHelper", navigator, ref DrawToneHelper);
CHelper.TryGetEnumValueFromXML("//root/Theme/TimerLook", navigator, ref TimerLook);
CHelper.TryGetEnumValueFromXML("//root/Theme/CoverLoading", navigator, ref CoverLoading);
#endregion Theme
#region Sound
CHelper.TryGetEnumValueFromXML<EPlaybackLib>("//root/Sound/PlayBackLib", navigator, ref PlayBackLib);
CHelper.TryGetEnumValueFromXML<ERecordLib>("//root/Sound/RecordLib", navigator, ref RecordLib);
#endregion Sound
#region Game
// Songfolder
value = string.Empty;
int i = 1;
while(CHelper.GetValueFromXML("//root/Game/SongFolder" + i.ToString(), navigator, ref value, value))
{
if (i == 1)
SongFolder.Clear();
SongFolder.Add(value);
value = string.Empty;
i++;
}
CHelper.TryGetEnumValueFromXML<ESongMenu>("//root/Game/SongMenu", navigator, ref SongMenu);
CHelper.TryGetEnumValueFromXML<ESongSorting>("//root/Game/SongSorting", navigator, ref SongSorting);
CHelper.TryGetFloatValueFromXML("//root/Game/ScoreAnimationTime", navigator, ref ScoreAnimationTime);
CHelper.TryGetEnumValueFromXML<ETimerMode>("//root/Game/TimerMode", navigator, ref TimerMode);
CHelper.TryGetIntValueFromXML("//root/Game/NumPlayer", navigator, ref NumPlayer);
CHelper.TryGetEnumValueFromXML("//root/Game/Tabs", navigator, ref Tabs);
CHelper.GetValueFromXML("//root/Game/Language", navigator, ref Language, Language);
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Game/LyricsOnTop", navigator, ref LyricsOnTop);
if ((ScoreAnimationTime > 0 && ScoreAnimationTime < 1) || ScoreAnimationTime < 0)
{
ScoreAnimationTime = 1;
}
if (NumPlayer < 1 || NumPlayer > CSettings.MaxNumPlayer)
NumPlayer = 2;
List<string> _Languages = new List<string>();
_Languages = CLanguage.GetLanguages();
bool _LangExists = false;
for (i = 0; i < _Languages.Count; i++)
{
if (_Languages[i] == Language)
{
_LangExists = true;
}
}
//TODO: What should we do, if English not exists?
if(_LangExists == false){
Language = "English";
}
CLanguage.SetLanguage(Language);
#endregion Game
#region Video
CHelper.TryGetEnumValueFromXML<EVideoDecoder>("//root/Video/VideoDecoder", navigator, ref VideoDecoder);
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Video/VideoBackgrounds", navigator, ref VideoBackgrounds);
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Video/VideoPreview", navigator, ref VideoPreview);
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Video/VideosInSongs", navigator, ref VideosInSongs);
#endregion Video
#region Record
MicConfig = new SMicConfig[CSettings.MaxNumPlayer];
value = string.Empty;
for (int p = 1; p <= CSettings.MaxNumPlayer; p++)
{
MicConfig[p - 1] = new SMicConfig(0);
CHelper.GetValueFromXML("//root/Record/MicConfig" + p.ToString() + "/DeviceName", navigator, ref MicConfig[p - 1].DeviceName, String.Empty);
CHelper.GetValueFromXML("//root/Record/MicConfig" + p.ToString() + "/DeviceDriver", navigator, ref MicConfig[p - 1].DeviceDriver, String.Empty);
CHelper.GetValueFromXML("//root/Record/MicConfig" + p.ToString() + "/InputName", navigator, ref MicConfig[p - 1].InputName, String.Empty);
CHelper.TryGetIntValueFromXML("//root/Record/MicConfig" + p.ToString() + "/Channel", navigator, ref MicConfig[p - 1].Channel);
}
CHelper.TryGetIntValueFromXML("//root/Record/MicDelay", navigator, ref MicDelay);
MicDelay = (int)(20 * Math.Round(MicDelay / 20.0));
if (MicDelay < 0)
MicDelay = 0;
if (MicDelay > 500)
MicDelay = 500;
#endregion Record
return true;
}
else return false;
}
public static bool SaveConfig()
{
XmlWriter writer = XmlWriter.Create(CSettings.sFileConfig, _settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
#region Info
writer.WriteStartElement("Info");
writer.WriteElementString("Version", CSettings.GetFullVersionText());
writer.WriteElementString("Time", System.DateTime.Now.ToString());
writer.WriteElementString("Platform", System.Environment.OSVersion.Platform.ToString());
writer.WriteElementString("OSVersion", System.Environment.OSVersion.ToString());
writer.WriteElementString("ProcessorCount", System.Environment.ProcessorCount.ToString());
writer.WriteElementString("Screens", Screen.AllScreens.Length.ToString());
writer.WriteElementString("PrimaryScreenResolution", Screen.PrimaryScreen.Bounds.Size.ToString());
writer.WriteElementString("Directory", System.Environment.CurrentDirectory.ToString());
writer.WriteEndElement();
#endregion Info
#region Debug
writer.WriteStartElement("Debug");
writer.WriteComment("DebugLevel: " + ListStrings(Enum.GetNames(typeof(EDebugLevel))));
writer.WriteElementString("DebugLevel", Enum.GetName(typeof(EDebugLevel), DebugLevel));
writer.WriteEndElement();
#endregion Debug
#region Graphics
writer.WriteStartElement("Graphics");
writer.WriteComment("Renderer: " + ListStrings(Enum.GetNames(typeof(ERenderer))));
writer.WriteElementString("Renderer", Enum.GetName(typeof(ERenderer), Renderer));
writer.WriteComment("TextureQuality: " + ListStrings(Enum.GetNames(typeof(ETextureQuality))));
writer.WriteElementString("TextureQuality", Enum.GetName(typeof(ETextureQuality), TextureQuality));
writer.WriteComment("Screen width and height (pixels)");
writer.WriteElementString("ScreenW", ScreenW.ToString());
writer.WriteElementString("ScreenH", ScreenH.ToString());
writer.WriteComment("AAMode: " + ListStrings(Enum.GetNames(typeof(EAntiAliasingModes))));
writer.WriteElementString("AAMode", Enum.GetName(typeof(EAntiAliasingModes), AAMode));
writer.WriteComment("Colors: " + ListStrings(Enum.GetNames(typeof(EColorDeep))));
writer.WriteElementString("Colors", Enum.GetName(typeof(EColorDeep), Colors));
writer.WriteComment("MaxFPS should be between 1..200");
writer.WriteElementString("MaxFPS", MaxFPS.ToString("#"));
writer.WriteComment("VSync: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("VSync", Enum.GetName(typeof(EOffOn), VSync));
writer.WriteComment("FullScreen: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("FullScreen", Enum.GetName(typeof(EOffOn), FullScreen));
writer.WriteComment("FadeTime should be between 0..3 Seconds");
writer.WriteElementString("FadeTime", FadeTime.ToString("#0.00"));
writer.WriteEndElement();
#endregion Graphics
#region Theme
writer.WriteStartElement("Theme");
writer.WriteComment("Theme name");
writer.WriteElementString("Name", Theme);
writer.WriteComment("Skin name");
writer.WriteElementString("Skin", Skin);
writer.WriteComment("Name of cover-theme");
writer.WriteElementString("Cover", CoverTheme);
writer.WriteComment("Draw note-lines:" + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("DrawNoteLines", Enum.GetName(typeof(EOffOn), DrawNoteLines));
writer.WriteComment("Draw tone-helper:" + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("DrawToneHelper", Enum.GetName(typeof(EOffOn), DrawToneHelper));
writer.WriteComment("Look of timer:" + ListStrings(Enum.GetNames(typeof(ETimerLook))));
writer.WriteElementString("TimerLook", Enum.GetName(typeof(ETimerLook), TimerLook));
writer.WriteComment("Cover Loading:" + ListStrings(Enum.GetNames(typeof(ECoverLoading))));
writer.WriteElementString("CoverLoading", Enum.GetName(typeof(ECoverLoading), CoverLoading));
writer.WriteEndElement();
#endregion Theme
#region Sound
writer.WriteStartElement("Sound");
writer.WriteComment("PlayBackLib: " + ListStrings(Enum.GetNames(typeof(EPlaybackLib))));
writer.WriteElementString("PlayBackLib", Enum.GetName(typeof(EPlaybackLib), PlayBackLib));
writer.WriteComment("RecordLib: " + ListStrings(Enum.GetNames(typeof(ERecordLib))));
writer.WriteElementString("RecordLib", Enum.GetName(typeof(ERecordLib), RecordLib));
writer.WriteEndElement();
#endregion Sound
#region Game
writer.WriteStartElement("Game");
writer.WriteComment("Game-Language:");
writer.WriteElementString("Language", Language);
// SongFolder
// Check, if program was started with songfolder-parameters
if (SongFolderOld.Count > 0)
{
//Write "old" song-folders to config.
writer.WriteComment("SongFolder: SongFolder1, SongFolder2, SongFolder3, ...");
for (int i = 0; i < SongFolderOld.Count; i++)
{
writer.WriteElementString("SongFolder" + (i + 1).ToString(), SongFolderOld[i]);
}
}
else
{
//Write "normal" song-folders to config.
writer.WriteComment("SongFolder: SongFolder1, SongFolder2, SongFolder3, ...");
for (int i = 0; i < SongFolder.Count; i++)
{
writer.WriteElementString("SongFolder" + (i + 1).ToString(), SongFolder[i]);
}
}
writer.WriteComment("SongMenu: " + ListStrings(Enum.GetNames(typeof(ESongMenu))));
writer.WriteElementString("SongMenu", Enum.GetName(typeof(ESongMenu), SongMenu));
writer.WriteComment("SongSorting: " + ListStrings(Enum.GetNames(typeof(ESongSorting))));
writer.WriteElementString("SongSorting", Enum.GetName(typeof(ESongSorting), SongSorting));
writer.WriteComment("ScoreAnimationTime: Values >= 1 or 0 for no animation. Time is in seconds.");
writer.WriteElementString("ScoreAnimationTime", ScoreAnimationTime.ToString());
writer.WriteComment("TimerMode: " + ListStrings(Enum.GetNames(typeof(ETimerMode))));
writer.WriteElementString("TimerMode", Enum.GetName(typeof(ETimerMode), TimerMode));
writer.WriteComment("NumPlayer: 1.." + CSettings.MaxNumPlayer.ToString());
writer.WriteElementString("NumPlayer", NumPlayer.ToString());
writer.WriteComment("Order songs in tabs: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("Tabs", Enum.GetName(typeof(EOffOn), Tabs));
writer.WriteComment("Lyrics also on Top of screen: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("LyricsOnTop", Enum.GetName(typeof(EOffOn), LyricsOnTop));
writer.WriteEndElement();
#endregion Game
#region Video
writer.WriteStartElement("Video");
writer.WriteComment("VideoDecoder: " + ListStrings(Enum.GetNames(typeof(EVideoDecoder))));
writer.WriteElementString("VideoDecoder", Enum.GetName(typeof(EVideoDecoder), VideoDecoder));
writer.WriteComment("VideoBackgrounds: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("VideoBackgrounds", Enum.GetName(typeof(EOffOn), VideoBackgrounds));
writer.WriteComment("VideoPreview: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("VideoPreview", Enum.GetName(typeof(EOffOn), VideoPreview));
writer.WriteComment("Show Videos while singing: " + ListStrings(Enum.GetNames(typeof(EOffOn))));
writer.WriteElementString("VideosInSongs", Enum.GetName(typeof(EOffOn), VideosInSongs));
writer.WriteEndElement();
#endregion Video
#region Record
writer.WriteStartElement("Record");
for (int p = 1; p <= CSettings.MaxNumPlayer; p++)
{
if (MicConfig[p - 1].DeviceName != String.Empty && MicConfig[p - 1].InputName != String.Empty && MicConfig[p - 1].Channel > 0)
{
writer.WriteStartElement("MicConfig" + p.ToString());
writer.WriteElementString("DeviceName", MicConfig[p - 1].DeviceName);
writer.WriteElementString("DeviceDriver", MicConfig[p - 1].DeviceDriver);
writer.WriteElementString("InputName", MicConfig[p - 1].InputName);
writer.WriteElementString("Channel", MicConfig[p - 1].Channel.ToString());
writer.WriteEndElement();
}
}
writer.WriteComment("Mic delay in ms. 0, 20, 40, 60 ... 500");
writer.WriteElementString("MicDelay", MicDelay.ToString());
writer.WriteEndElement();
#endregion Record
// End of File
writer.WriteEndElement(); //end of root
writer.WriteEndDocument();
writer.Flush();
writer.Close();
return true;
}
/// <summary>
/// Calculates the maximum cycle time to reach the MaxFPS value.
/// </summary>
public static float CalcCycleTime()
{
return (1f / MaxFPS)*1000f;
}
/// <summary>
/// Checks, if there is a mic-configuration
/// </summary>
/// <returns></returns>
public static bool IsMicConfig()
{
SRecordDevice[] Devices = CSound.RecordGetDevices();
if (Devices == null)
return false;
for (int dev = 0; dev < Devices.Length; dev++)
{
for (int inp = 0; inp < Devices[dev].Inputs.Count; inp++)
{
if (Devices[dev].Inputs[inp].PlayerChannel1 != 0 || Devices[dev].Inputs[inp].PlayerChannel2 != 0)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Checks, if there is a mic-configuration
/// </summary>
/// <param name="player">Player-Number</param>
/// <returns></returns>
public static bool IsMicConfig(int player)
{
SRecordDevice[] Devices = CSound.RecordGetDevices();
if (Devices == null)
return false;
if (Devices != null)
{
for (int dev = 0; dev < Devices.Length; dev++)
{
for (int inp = 0; inp < Devices[dev].Inputs.Count; inp++)
{
if (Devices[dev].Inputs[inp].PlayerChannel1 == player || Devices[dev].Inputs[inp].PlayerChannel2 == player)
{
return true;
}
}
}
return false;
}
return false;
}
/// <summary>
/// Try to assign automatically player 1 and 2 to usb-mics.
/// </summary>
public static bool AutoAssignMics()
{
//Look for (usb-)mic
//SRecordDevice[] Devices = new SRecordDevice[CSound.RecordGetDevices().Length];
SRecordDevice[] Devices = CSound.RecordGetDevices();
if (Devices == null)
return false;
for (int dev = 0; dev < Devices.Length; dev++)
{
//Has Device some signal-names in name -> This could be a (usb-)mic
if (Regex.IsMatch(Devices[dev].Name, @"Usb|Wireless", RegexOptions.IgnoreCase))
{
//Check if there are inputs.
if (Devices[dev].Inputs.Count >= 1)
{
//Check if there is one or more channels
if (Devices[dev].Inputs[0].Channels >= 2)
{
//Set this device to player 1
MicConfig[0].DeviceName = Devices[dev].Name;
MicConfig[0].DeviceDriver = Devices[dev].Driver;
MicConfig[0].InputName = Devices[dev].Inputs[0].Name;
MicConfig[0].Channel = 1;
//Set this device to player 2
MicConfig[1].DeviceName = Devices[dev].Name;
MicConfig[1].DeviceDriver = Devices[dev].Driver;
MicConfig[1].InputName = Devices[dev].Inputs[0].Name;
MicConfig[1].Channel = 2;
return true;
}
}
}
}
//If no usb-mics found -> Look for Devices with "mic" or "mik"
for (int dev = 0; dev < Devices.Length; dev++)
{
//Has Device some signal-names in name -> This could be a mic
if (Regex.IsMatch(Devices[dev].Name, @"Mic|Mik", RegexOptions.IgnoreCase))
{
//Check if there are inputs.
if (Devices[dev].Inputs.Count >= 1)
{
bool micfound = false;
//Check if there is one or more channels
if (Devices[dev].Inputs[0].Channels >= 1)
{
//Set this device to player 1
MicConfig[0].DeviceName = Devices[dev].Name;
MicConfig[0].DeviceDriver = Devices[dev].Driver;
MicConfig[0].InputName = Devices[dev].Inputs[0].Name;
MicConfig[0].Channel = 1;
micfound = true;
}
if (Devices[dev].Inputs[0].Channels >= 2)
{
//Set this device to player 2
MicConfig[1].DeviceName = Devices[dev].Name;
MicConfig[1].DeviceDriver = Devices[dev].Driver;
MicConfig[1].InputName = Devices[dev].Inputs[0].Name;
MicConfig[1].Channel = 2;
micfound = true;
}
if (micfound)
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// Load command-line-parameters and their values to lists.
/// </summary>
/// <param name="args">Parameters</param>
public static void LoadCommandLineParams(string[] args)
{
Regex SpliterParam = new Regex(@"-{1,2}|\/", RegexOptions.IgnoreCase);
//Complete argument string
string arguments = string.Empty;
foreach (string arg in args)
{
arguments += arg + " ";
}
args = SpliterParam.Split(arguments);
foreach (string text in args)
{
Regex SpliterVal = new Regex(@"\s", RegexOptions.IgnoreCase);
//Array for parts of an arg
string[] parts;
//split arg with Spilter-Regex and save in parts
parts = SpliterVal.Split(text, 2);
switch (parts.Length)
{
//Only found a parameter
case 1:
if (!Regex.IsMatch(parts[0], @"\s") && parts[0] != string.Empty)
{
//Add parameter
_Params.Add(parts[0]);
//Add value
_Values.Add("");
}
break;
//Found parameter and value
case 2:
if (!Regex.IsMatch(parts[0], @"\s") && parts[0] != string.Empty)
{
//Add parameter
_Params.Add(parts[0]);
//Add value
_Values.Add(parts[1]);
}
break;
}
}
}
/// <summary>
/// Apply command-line-parameters (before reading config.xml)
/// </summary>
public static void UseCommandLineParamsBefore(){
//Check each parameter
for (int i = 0; i < _Params.Count; i++)
{
//Switch parameter as lower case
string param = _Params[i];
param = param.ToLower();
string value = _Values[i];
switch (param)
{
case "configfile":
//Check if value is valid
if (CheckFile(value))
{
CSettings.sFileConfig = value;
}
break;
case "scorefile":
//Check if value is valid
if (CheckFile(value))
{
CSettings.sFileHighscoreDB = value;
}
break;
}
}
}
/// <summary>
/// Apply command-line-parameters (after reading config.xml)
/// </summary>
public static void UseCommandLineParamsAfter()
{
//Check each parameter
for (int i = 0; i < _Params.Count; i++)
{
//Switch parameter as lower case
string param = _Params[i];
param = param.ToLower();
string value = _Values[i];
switch (param)
{
case "songfolder":
//Check if SongFolders from config.xml are saved
if (SongFolderOld.Count == 0)
{
SongFolderOld.Clear();
SongFolderOld.AddRange(SongFolder);
SongFolder.Clear();
}
//Add parameter-value to SongFolder
SongFolder.Add(value);
break;
case "songpath":
//Check if SongFolders from config.xml are saved
if (SongFolderOld.Count == 0)
{
SongFolderOld.Clear();
SongFolderOld.AddRange(SongFolder);
SongFolder.Clear();
}
//Add parameter-value to SongFolder
SongFolder.Add(value);
break;
}
}
}
private static bool CheckFile(string value)
{
char [] chars = Path.GetInvalidPathChars();
for(int i=0; i<chars.Length; i++){
if(value.Contains(chars[i].ToString())){
return false;
}
}
if (Path.GetFileName(value) == string.Empty)
{
return false;
}
if (!Path.HasExtension(value))
{
return false;
}
return true;
}
/// <summary>
/// Concat strings into one string with ", " as separator.
/// </summary>
public static string ListStrings(string[] str)
{
string _Result = string.Empty;
for (int i = 0; i < str.Length; i++)
{
_Result += str[i];
if(i < str.Length - 1)
_Result += ", ";
}
return _Result;
}
}
}
+299
View File
@@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Base
{
struct SCover
{
public string Name;
public string Value;
public STexture Texture;
}
struct SCoverTheme
{
public string Name;
public string Folder;
public string File;
}
abstract class CCover
{
private static XmlWriterSettings _settings = new XmlWriterSettings();
private static List<SCover> _Cover = new List<SCover>();
private static List<SCoverTheme> _CoverThemes = new List<SCoverTheme>();
private static STexture _NoCover = new STexture(-1);
private static Object _MutexCover = new Object();
public static STexture NoCover
{
get { return _NoCover; }
}
public static void Init()
{
_settings.Indent = true;
_settings.Encoding = Encoding.UTF8;
_settings.ConformanceLevel = ConformanceLevel.Document;
LoadCoverThemes();
LoadCover(CConfig.CoverTheme);
}
/// <summary>
/// Returns an array of CoverThemes-Names
/// </summary>
public static string[] CoverThemes
{
get
{
List<string> CoverThemes = new List<string>();
for (int i = 0; i < _CoverThemes.Count; i++)
{
CoverThemes.Add(_CoverThemes[i].Name);
}
return CoverThemes.ToArray();
}
}
/// <summary>
/// Returns the current cover theme index
/// </summary>
/// <returns></returns>
public static int GetCoverThemeIndex()
{
for (int i = 0; i < _CoverThemes.Count; i++)
{
if (_CoverThemes[i].Name == CConfig.CoverTheme)
{
return i;
}
}
return -1;
}
/// <summary>
/// Returns a STexture for a given cover name. Returns "NoCover" if the cover does not exist.
/// </summary>
public static STexture Cover(string Name)
{
STexture cov = _NoCover;
lock (_MutexCover)
{
foreach (SCover cover in _Cover)
{
if (cover.Name == Name)
{
cov = cover.Texture;
break;
}
}
}
return cov;
}
/// <summary>
/// Returns true if a cover with the given name exists.
/// </summary>
public static bool CoverExists(string Name)
{
STexture cov = _NoCover;
lock (_MutexCover)
{
foreach (SCover cover in _Cover)
{
if (cover.Name == Name)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Reloads cover to use a new cover-theme
/// </summary>
public static void ReloadCover()
{
foreach (SCover cover in _Cover)
{
STexture texture = cover.Texture;
CDraw.RemoveTexture(ref texture);
}
_Cover.Clear();
LoadCover(CConfig.CoverTheme);
}
/// <summary>
/// Returns a SCoverTheme by cover-theme-name
/// </summary>
private static SCoverTheme CoverTheme(string coverThemeName)
{
SCoverTheme coverTheme = new SCoverTheme();
for (int i = 0; i < _CoverThemes.Count; i++)
{
if (_CoverThemes[i].Name == coverThemeName)
{
coverTheme = _CoverThemes[i];
break;
}
}
return coverTheme;
}
/// <summary>
/// Loads all cover-themes to list.
/// </summary>
private static void LoadCoverThemes()
{
_CoverThemes.Clear();
CHelper Helper = new CHelper();
string path = CSettings.sFolderCover;
List<string> files = Helper.ListFiles(path, "*.xml", false);
foreach (string file in files)
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(Path.Combine(path, file));
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception)
{
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
if (loaded)
{
SCoverTheme coverTheme = new SCoverTheme();
CHelper.GetValueFromXML("//root/Info/Name", navigator, ref coverTheme.Name, String.Empty);
CHelper.GetValueFromXML("//root/Info/Folder", navigator, ref coverTheme.Folder, String.Empty);
if (coverTheme.Folder != String.Empty && coverTheme.Name != String.Empty)
{
coverTheme.File = file;
_CoverThemes.Add(coverTheme);
}
}
}
}
/// <summary>
/// Loads all cover which are defined in the cover config file.
/// </summary>
private static void LoadCover(string coverThemeName)
{
SCoverTheme coverTheme = new SCoverTheme();
coverTheme = CoverTheme(coverThemeName);
if (coverTheme.Name != String.Empty)
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(Path.Combine(CSettings.sFolderCover, coverTheme.File));
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception)
{
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
if (loaded)
{
lock (_MutexCover)
{
_Cover.Clear();
List<string> cover = CHelper.GetValuesFromXML("Cover", navigator);
for (int i = 1; i <= cover.Count; i++)
{
SCover sk = new SCover();
string name = String.Empty;
string value = String.Empty;
CHelper.GetValueFromXML("//root/Cover/Cover" + i + "/Name", navigator, ref name, String.Empty);
CHelper.GetValueFromXML("//root/Cover/Cover" + i + "/Path", navigator, ref value, String.Empty);
sk.Name = name;
sk.Value = Path.Combine(coverTheme.Folder,value);
if (File.Exists(Path.Combine(CSettings.sFolderCover, Path.Combine(coverTheme.Folder, value))))
{
sk.Texture = CDraw.AddTexture(Path.Combine(CSettings.sFolderCover, Path.Combine(coverTheme.Folder, value)));
}
else
{
sk.Texture = _NoCover;
}
_Cover.Add(sk);
if (sk.Name == "NoCover")
{
_NoCover = sk.Texture;
}
}
}
}
CHelper Helper = new CHelper();
List<string> files = new List<string>();
files.AddRange(Helper.ListFiles(Path.Combine(CSettings.sFolderCover, coverTheme.Folder), "*.png", true, true));
files.AddRange(Helper.ListFiles(Path.Combine(CSettings.sFolderCover, coverTheme.Folder), "*.jpg", true, true));
files.AddRange(Helper.ListFiles(Path.Combine(CSettings.sFolderCover, coverTheme.Folder), "*.jpeg", true, true));
files.AddRange(Helper.ListFiles(Path.Combine(CSettings.sFolderCover, coverTheme.Folder), "*.bmp", true, true));
foreach (string file in files)
{
string name = Path.GetFileNameWithoutExtension(file);
if (!CoverExists(name))
{
SCover sk = new SCover();
string value = String.Empty;
sk.Name = name;
sk.Value = Path.Combine(coverTheme.Folder,Path.GetFileName(file));
sk.Texture = CDraw.AddTexture(Path.Combine(CSettings.sFolderCover, sk.Value));
_Cover.Add(sk);
}
}
}
}
}
}
+635
View File
@@ -0,0 +1,635 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Data.SQLite;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Song;
namespace Vocaluxe.Base
{
static class CDataBase
{
private static string _HighscoreFilePath;
private static string _CoverFilePath;
public static void Init()
{
_HighscoreFilePath = Path.Combine(System.Environment.CurrentDirectory, CSettings.sFileHighscoreDB);
_CoverFilePath = Path.Combine(System.Environment.CurrentDirectory, CSettings.sFileCoverDB);
InitHighscoreDB();
InitCoverDB();
}
#region Highscores
public static int AddScore(SPlayer player)
{
int lastInsertID = -1;
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + _HighscoreFilePath;
SQLiteCommand command;
try
{
connection.Open();
}
catch (Exception)
{
return -1;
}
command = new SQLiteCommand(connection);
int DataBaseSongID = GetDataBaseSongID(player, command);
if (DataBaseSongID >= 0)
{
int Medley = 0;
if (player.Medley)
Medley = 1;
int Duet = 0;
if (player.Duet)
Duet = 1;
command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) " +
"VALUES (@SongID, @PlayerName, @Score, @LineNr, @Date, @Medley, @Duet, @Difficulty)";
command.Parameters.Add("@SongID", System.Data.DbType.Int32, 0).Value = DataBaseSongID;
command.Parameters.Add("@PlayerName", System.Data.DbType.String, 0).Value = player.Name;
command.Parameters.Add("@Score", System.Data.DbType.Int32, 0).Value = (int)Math.Round(player.Points);
command.Parameters.Add("@LineNr", System.Data.DbType.Int32, 0).Value = (int)player.LineNr;
command.Parameters.Add("@Date", System.Data.DbType.Int64, 0).Value = player.DateTicks;
command.Parameters.Add("@Medley", System.Data.DbType.Int32, 0).Value = Medley;
command.Parameters.Add("@Duet", System.Data.DbType.Int32, 0).Value = Duet;
command.Parameters.Add("@Difficulty", System.Data.DbType.Int32, 0).Value = (int)player.Difficulty;
command.ExecuteNonQuery();
//Read last insert line
command.CommandText = "SELECT id FROM Scores ORDER BY Date DESC LIMIT 0, 1";
SQLiteDataReader reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
lastInsertID = reader.GetInt32(0);
}
reader.Close();
reader.Dispose();
}
}
command.Dispose();
connection.Close();
connection.Dispose();
return lastInsertID;
}
public static void LoadScore(ref List<SScores> Score, SPlayer player)
{
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + _HighscoreFilePath;
SQLiteCommand command;
Score = new List<SScores>();
try
{
connection.Open();
}
catch (Exception)
{
return;
}
command = new SQLiteCommand(connection);
int Medley = 0;
if (player.Medley)
Medley = 1;
int Duet = 0;
if (player.Duet)
Duet = 1;
int DataBaseSongID = GetDataBaseSongID(player, command);
if (DataBaseSongID >= 0)
{
command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id FROM Scores " +
"WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet " +
"ORDER BY [Score] DESC";
command.Parameters.Add("@SongID", System.Data.DbType.Int32, 0).Value = DataBaseSongID;
command.Parameters.Add("@Medley", System.Data.DbType.Int32, 0).Value = Medley;
command.Parameters.Add("@Duet", System.Data.DbType.Int32, 0).Value = Duet;
SQLiteDataReader reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
SScores score = new SScores();
score.Name = reader.GetString(0);
score.Score = reader.GetInt32(1);
score.Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy");
score.Difficulty = (EGameDifficulty)reader.GetInt32(3);
score.LineNr = reader.GetInt32(4);
score.ID = reader.GetInt32(5);
Score.Add(score);
}
reader.Close();
reader.Dispose();
}
}
command.Dispose();
connection.Close();
connection.Dispose();
}
private static int GetDataBaseSongID(SPlayer player, SQLiteCommand command)
{
CSong song = CSongs.GetSong(player.SongID);
if (song == null)
return -1;
command.CommandText = "SELECT id FROM Songs WHERE [Title] = @title AND [Artist] = @artist";
command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = song.Title;
command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = song.Artist;
SQLiteDataReader reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null && reader.HasRows)
{
reader.Read();
int id = reader.GetInt32(0);
reader.Close();
reader.Dispose();
return id;
}
else
{
if (reader != null)
reader.Close();
command.CommandText = "INSERT INTO Songs (Title, Artist, NumPlayed) " +
"VALUES (@title, @artist, 0)";
command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = song.Title;
command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = song.Artist;
command.ExecuteNonQuery();
command.CommandText = "SELECT id FROM Songs WHERE [Title] = @title AND [Artist] = @artist";
command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = song.Title;
command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = song.Artist;
reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null)
{
reader.Read();
int id = reader.GetInt32(0);
reader.Close();
reader.Dispose();
return id;
}
}
if (reader != null)
{
reader.Close();
reader.Dispose();
}
return -1;
}
private static bool InitHighscoreDB()
{
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + _HighscoreFilePath;
SQLiteCommand command;
try
{
connection.Open();
}
catch (Exception)
{
return false;
}
command = new SQLiteCommand(connection);
command.CommandText = "SELECT Value FROM Version";
SQLiteDataReader reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
;
}
if (reader == null)
{
// create new database/tables
CreateHighscoreDB();
}
else if (reader.FieldCount == 0)
{
// create new database/tables
CreateHighscoreDB();
}
else
{
reader.Read();
if (reader.GetInt32(0) < CSettings.iDatabaseHighscoreVersion)
{
// update database
}
}
if (reader != null)
{
reader.Close();
reader.Dispose();
}
command.Dispose();
connection.Close();
connection.Dispose();
return true;
}
private static void CreateHighscoreDB()
{
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + _HighscoreFilePath;
SQLiteCommand command;
try
{
connection.Open();
}
catch (Exception)
{
return;
}
command = new SQLiteCommand(connection);
command.CommandText = "CREATE TABLE IF NOT EXISTS Version ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Value INTEGER NOT NULL);";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Version (id, Value) VALUES(NULL, " + CSettings.iDatabaseHighscoreVersion.ToString() + ")";
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE IF NOT EXISTS Songs ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"Artist TEXT NOT NULL, Title TEXT NOT NULL, NumPlayed INTEGER);";
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE IF NOT EXISTS Scores ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"SongID INTEGER NOT NULL, PlayerName TEXT NOT NULL, Score INTEGER NOT NULL, LineNr INTEGER NOT NULL, Date BIGINT NOT NULL, " +
"Medley INTEGER NOT NULL, Duet INTEGER NOT NULL, Difficulty INTEGER NOT NULL);";
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
/*
// Auslesen des zuletzt eingefügten Datensatzes.
command.CommandText = "SELECT id, name FROM beispiel ORDER BY id DESC LIMIT 0, 1";
while (reader.Read())
{
Console.WriteLine("Dies ist der {0}. eingefügte Datensatz mit dem Wert: \"{1}\"", reader[0].ToString(), reader[1].ToString());
}
*/
}
#endregion Highscores
#region Cover
public static bool GetCover(string CoverPath, ref STexture tex, int MaxSize)
{
bool result = false;
if (!File.Exists(CoverPath))
{
CLog.LogError("Can't find File: " + CoverPath);
return false;
}
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + _CoverFilePath;
SQLiteCommand command;
try
{
connection.Open();
}
catch (Exception)
{
return false;
}
command = new SQLiteCommand(connection);
command.CommandText = "SELECT id, width, height FROM Cover WHERE [Path] = @path";
command.Parameters.Add("@path", System.Data.DbType.String, 0).Value = CoverPath;
SQLiteDataReader reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null && reader.HasRows)
{
reader.Read();
int id = reader.GetInt32(0);
int w = reader.GetInt32(1);
int h = reader.GetInt32(2);
reader.Close();
command.CommandText = "SELECT Data FROM CoverData WHERE CoverID = " + id.ToString();
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader.HasRows)
{
result = true;
reader.Read();
byte[] data = GetBytes(reader);
tex = CDraw.AddTexture(w, h, ref data);
}
}
else
{
if (reader != null)
reader.Close();
Bitmap origin;
try
{
origin = new Bitmap(CoverPath);
}
catch (Exception)
{
CLog.LogError("Error loading Texture: " + CoverPath);
tex = new STexture(-1);
if (reader != null)
{
reader.Close();
reader.Dispose();
}
command.Dispose();
connection.Close();
connection.Dispose();
return false;
}
int w = MaxSize;
int h = MaxSize;
if (origin.Width >= origin.Height && origin.Width > w)
h = (int)Math.Round((float)w / origin.Width * origin.Height);
else if (origin.Height > origin.Width && origin.Height > h)
w = (int)Math.Round((float)h / origin.Height * origin.Width);
Bitmap bmp = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(origin, new Rectangle(0, 0, w, h));
g.Dispose();
tex = CDraw.AddTexture(bmp);
byte[] data = new byte[w * h * 4];
BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Marshal.Copy(bmp_data.Scan0, data, 0, w*h*4);
bmp.UnlockBits(bmp_data);
bmp.Dispose();
command.CommandText = "INSERT INTO Cover (Path, width, height) " +
"VALUES (@path, " + w.ToString() + ", " + h.ToString() + ")";
command.Parameters.Add("@path", System.Data.DbType.String, 0).Value = CoverPath;
command.ExecuteNonQuery();
command.CommandText = "SELECT id FROM Cover WHERE [Path] = @path";
command.Parameters.Add("@path", System.Data.DbType.String, 0).Value = CoverPath;
reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null)
{
reader.Read();
int id = reader.GetInt32(0);
reader.Close();
command.CommandText = "INSERT INTO CoverData (CoverID, Data) " +
"VALUES ('" + id.ToString() + "', @data)";
command.Parameters.Add("@data", System.Data.DbType.Binary, 20).Value = data;
command.ExecuteReader();
result = true;
}
}
if (reader != null)
{
reader.Close();
reader.Dispose();
}
command.Dispose();
connection.Close();
connection.Dispose();
return result;
}
private static bool InitCoverDB()
{
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + _CoverFilePath;
SQLiteCommand command;
try
{
connection.Open();
}
catch (Exception)
{
return false;
}
command = new SQLiteCommand(connection);
command.CommandText = "SELECT Value FROM Version";
SQLiteDataReader reader = null;
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
;
}
if (reader == null)
{
// create new database/tables
CreateCoverDB();
}
else if (reader.FieldCount == 0)
{
// create new database/tables
CreateCoverDB();
}
else
{
reader.Read();
if (reader.GetInt32(0) < CSettings.iDatabaseHighscoreVersion)
{
// update database
}
}
if (reader != null)
{
reader.Close();
reader.Dispose();
}
command.Dispose();
connection.Close();
connection.Dispose();
return true;
}
private static void CreateCoverDB()
{
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + _CoverFilePath;
SQLiteCommand command;
try
{
connection.Open();
}
catch (Exception)
{
return;
}
command = new SQLiteCommand(connection);
command.CommandText = "CREATE TABLE IF NOT EXISTS Version ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Value INTEGER NOT NULL);";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Version (id, Value) VALUES(NULL, " + CSettings.iDatabaseCoverVersion.ToString() + ")";
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE IF NOT EXISTS Cover ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"Path TEXT NOT NULL, width INTEGER NOT NULL, height INTEGER NOT NULL);";
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE IF NOT EXISTS CoverData ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"CoverID INTEGER NOT NULL, Data BLOB NOT NULL);";
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
}
#endregion Cover
private static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
byte[] buffer = new byte[CHUNK_SIZE];
long bytesRead;
long fieldOffset = 0;
using (MemoryStream stream = new MemoryStream())
{
while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
{
byte[] actualRead = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, actualRead, 0, (int)bytesRead);
stream.Write(actualRead, 0, actualRead.Length);
fieldOffset += bytesRead;
}
return stream.ToArray();
}
}
}
}
+734
View File
@@ -0,0 +1,734 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Menu;
namespace Vocaluxe.Base
{
static class CDraw
{
private static Object mutex = new object();
private static IDraw _Draw = null;
public static void InitDraw()
{
switch (CConfig.Renderer)
{
case ERenderer.TR_CONFIG_SOFTWARE:
_Draw = new CDrawWinForm();
break;
case ERenderer.TR_CONFIG_OPENGL:
_Draw = new COpenGL();
break;
case ERenderer.TR_CONFIG_DIRECT3D:
_Draw = new CDirect3D();
break;
default:
_Draw = new CDrawWinForm();
break;
}
_Draw.Init();
}
public static void MainLoop()
{
CGraphics.InitFirstScreen();
_Draw.MainLoop();
}
public static bool Unload()
{
return _Draw.Unload();
}
public static int GetScreenWidth()
{
lock (mutex)
{
return _Draw.GetScreenWidth();
}
}
public static int GetScreenHeight()
{
lock (mutex)
{
return _Draw.GetScreenHeight();
}
}
public static RectangleF GetTextBounds(CText text)
{
lock (mutex)
{
return _Draw.GetTextBounds(text);
}
}
public static RectangleF GetTextBounds(CText text, float Height)
{
lock (mutex)
{
return _Draw.GetTextBounds(text, Height);
}
}
public static void DrawLine(int a, int r, int g, int b, int w, int x1, int y1, int x2, int y2)
{
lock (mutex)
{
_Draw.DrawLine(a, r, g, b, w, x1, y1, x2, y2);
}
}
public static void DrawRect(SColorF Color, SRectF Rect, float Thickness)
{
lock (mutex)
{
if (Thickness <= 0f)
return;
_Draw.DrawColor(Color, new SRectF(Rect.X - Thickness / 2, Rect.Y - Thickness / 2, Rect.W + Thickness, Thickness, Rect.Z));
_Draw.DrawColor(Color, new SRectF(Rect.X - Thickness / 2, Rect.Y + Rect.H - Thickness / 2, Rect.W + Thickness, Thickness, Rect.Z));
_Draw.DrawColor(Color, new SRectF(Rect.X - Thickness / 2, Rect.Y - Thickness / 2, Thickness, Rect.H + Thickness, Rect.Z));
_Draw.DrawColor(Color, new SRectF(Rect.X + Rect.W - Thickness / 2, Rect.Y - Thickness / 2, Thickness, Rect.H + Thickness, Rect.Z));
}
}
public static void DrawColor(SColorF color, SRectF rect)
{
lock (mutex)
{
_Draw.DrawColor(color, rect);
}
}
public static void ClearScreen()
{
lock (mutex)
{
_Draw.ClearScreen();
}
}
public static STexture CopyScreen()
{
lock (mutex)
{
return _Draw.CopyScreen();
}
}
public static void CopyScreen(ref STexture Texture)
{
lock (mutex)
{
_Draw.CopyScreen(ref Texture);
}
}
public static void MakeScreenShot()
{
lock (mutex)
{
_Draw.MakeScreenShot();
}
}
// Draw Basic Text (must be deleted later)
public static void DrawText(string Text, int x, int y, int h)
{
lock (mutex)
{
_Draw.DrawText(Text, x, y, h);
}
}
public static STexture AddTexture(Bitmap Bitmap)
{
lock (mutex)
{
return _Draw.AddTexture(Bitmap);
}
}
public static STexture AddTexture(string TexturePath)
{
lock (mutex)
{
return _Draw.AddTexture(TexturePath);
}
}
public static STexture AddTexture(string TexturePath, int MaxSize)
{
lock (mutex)
{
if (MaxSize == 0)
return _Draw.AddTexture(TexturePath);
if (!System.IO.File.Exists(TexturePath))
return new STexture(-1);
Bitmap origin = new Bitmap(TexturePath);
int w = MaxSize;
int h = MaxSize;
if (origin.Width >= origin.Height && origin.Width > w)
h = (int)Math.Round((float)w / origin.Width * origin.Height);
else if (origin.Height > origin.Width && origin.Height > h)
w = (int)Math.Round((float)h / origin.Height * origin.Width);
Bitmap bmp = new Bitmap(origin, w, h);
STexture tex = _Draw.AddTexture(bmp);
bmp.Dispose();
return tex;
}
}
public static STexture AddTexture(int W, int H, IntPtr Data)
{
lock (mutex)
{
return _Draw.AddTexture(W, H, Data);
}
}
public static STexture AddTexture(int W, int H, ref byte[] Data)
{
lock (mutex)
{
return _Draw.AddTexture(W, H, ref Data);
}
}
public static bool UpdateTexture(ref STexture Texture, ref byte[] Data)
{
lock (mutex)
{
return _Draw.UpdateTexture(ref Texture, ref Data);
}
}
public static bool UpdateTexture(ref STexture Texture, IntPtr Data)
{
lock (mutex)
{
return _Draw.UpdateTexture(ref Texture, Data);
}
}
public static void RemoveTexture(ref STexture Texture)
{
lock (mutex)
{
_Draw.RemoveTexture(ref Texture);
}
}
public static void DrawTexture(STexture Texture)
{
lock (mutex)
{
_Draw.DrawTexture(Texture);
}
}
public static void DrawTexture(STexture Texture, SRectF rect)
{
lock (mutex)
{
_Draw.DrawTexture(Texture, rect);
}
}
public static void DrawTexture(STexture Texture, SRectF rect, SColorF color)
{
lock (mutex)
{
_Draw.DrawTexture(Texture, rect, color);
}
}
public static void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds)
{
lock (mutex)
{
_Draw.DrawTexture(Texture, rect, color, bounds);
}
}
public static void DrawTexture(STexture Texture, SRectF rect, SColorF color,bool mirrored)
{
lock (mutex)
{
_Draw.DrawTexture(Texture, rect, color, mirrored);
}
}
public static void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored)
{
lock (mutex)
{
_Draw.DrawTexture(Texture, rect, color, bounds, mirrored);
}
}
public static void DrawTexture(STexture Texture, SRectF rect, SColorF color, float begin, float end)
{
lock (mutex)
{
_Draw.DrawTexture(Texture, rect, color, begin, end);
}
}
public static void DrawTextureReflection(STexture Texture, SRectF rect, SColorF color, SRectF bounds, float space, float height)
{
lock (mutex)
{
_Draw.DrawTextureReflection(Texture, rect, color, bounds, space, height);
}
}
public static int TextureCount()
{
lock (mutex)
{
return _Draw.TextureCount();
}
}
}
enum EParticeType
{
Twinkle,
Star,
Snow,
Flare,
PerfNoteStar
}
class CParticle
{
#region private vars
private string _TextureName;
private SRectF _Rect;
private float _Size;
private SColorF _Color;
private float _Alpha;
private float _Angle; //0..360°
private float _MaxAge; //[s]
private float _Age; //[s]
private float _Vx; //movement speed in x-axis [pix/s]
private float _Vy; //movement speed in y-axis [pix/s]
private float _Vr; //rotation speed [rpm]
private float _Rotation; //start rotation 0..360°
private float _Vsize; //size changing speed: period [s]
private float _LastTime;
private EParticeType _Type;
private Stopwatch _Timer;
#endregion private vars
#region public vars
public bool Visible;
public float Alpha2 = 1f;
public float X
{
get { return _Rect.X; }
set { _Rect.X = value; }
}
public float Y
{
get { return _Rect.Y; }
set { _Rect.Y = value; }
}
public float Size
{
get { return _Size; }
set
{
_Rect.W = value;
_Rect.H = value;
_Size = value;
}
}
public float Alpha
{
get { return _Alpha; }
set { _Alpha = value; }
}
public SColorF Color
{
get { return _Color; }
set { _Color = value; }
}
public bool IsAlive
{
get { return (_Age < _MaxAge || _MaxAge == 0f); }
}
#endregion public vars
#region Constructors
public CParticle(string textureName, SColorF color, float x, float y, float size, float maxage, float z, float vx, float vy, float vr, float vsize, EParticeType type)
{
_TextureName = textureName;
_Color = color;
_Rect = new SRectF(x, y, size, size, z);
_Size = size;
_Alpha = 1f;
_Angle = 0f;
_Vx = vx;
_Vy = vy;
_Vr = vr;
_Vsize = vsize;
_LastTime = 0f;
_Type = type;
_Timer = new Stopwatch();
_Age = 0f;
_MaxAge = maxage;
_Rotation = (float)(CGame.Rand.NextDouble() * 360.0);
}
#endregion Constructors
public void Update()
{
if (!IsAlive)
return;
if (!_Timer.IsRunning)
_Timer.Start();
float CurrentTime = _Timer.ElapsedMilliseconds / 1000f;
float timediff = CurrentTime - _LastTime;
_Age = CurrentTime;
// update alpha
if (_MaxAge > 0f)
{
switch (_Type)
{
case EParticeType.Twinkle:
_Alpha = 1f - _Age / _MaxAge;
break;
case EParticeType.Star:
_Alpha = 1f - _Age / _MaxAge;
break;
case EParticeType.Snow:
_Alpha = (float)Math.Sqrt((Math.Sin(_Age / _MaxAge * Math.PI * 2 - 0.5 * Math.PI) + 1) / 2);
break;
case EParticeType.Flare:
_Alpha = 1f - _Age / _MaxAge;
break;
case EParticeType.PerfNoteStar:
_Alpha = 1f - _Age / _MaxAge;
break;
default:
break;
}
}
// update position
switch (_Type)
{
case EParticeType.Twinkle:
X += _Vx * timediff;
Y += _Vy * timediff;
break;
case EParticeType.Star:
X += _Vx * timediff;
Y += _Vy * timediff;
break;
case EParticeType.Snow:
int maxy = (int)Math.Round(CSettings.iRenderH - _Size * 0.4f);
if (Math.Round(Y) < maxy)
{
float vdx = 0f;
if (_Vx != 0)
vdx = (float)Math.Sin(CurrentTime / _Vx * Math.PI);
X += _Vx * timediff * (0.5f + vdx);
Y += _Vy * timediff * (vdx * vdx / 2f + 0.5f);
if (Y >= maxy)
Y = maxy;
}
break;
case EParticeType.Flare:
X += _Vx * timediff;
Y += _Vy * timediff;
break;
case EParticeType.PerfNoteStar:
X += _Vx * timediff;
Y += _Vy * timediff;
break;
default:
break;
}
// update size
if (_Vsize != 0f)
{
float size = _Size;
switch (_Type)
{
case EParticeType.Twinkle:
size = _Size * (1f - CurrentTime / _Vsize);
break;
case EParticeType.Star:
size = _Size * (1f - CurrentTime / _Vsize);
break;
case EParticeType.Snow:
size = _Size * (float)Math.Sqrt((Math.Sin(CurrentTime / _Vsize * Math.PI * 2 - 0.5 * Math.PI) + 1) / 2);
break;
case EParticeType.Flare:
size = _Size * (1f - CurrentTime / _Vsize);
break;
case EParticeType.PerfNoteStar:
size = _Size * (1f - CurrentTime / _Vsize);
break;
default:
break;
}
_Rect.X += (_Rect.W - size) / 2f;
_Rect.Y += (_Rect.H - size) / 2f;
_Rect.W = size;
_Rect.H = size;
}
// update rotation
if (_Vr != 0f)
{
float r = CurrentTime * _Vr / 60f;
_Angle = _Rotation + 360f * (r - (float)Math.Floor(r));
_Rect.Rotation = _Angle;
}
_LastTime = CurrentTime;
}
public void Pause()
{
_Timer.Stop();
}
public void Resume()
{
_Timer.Start();
}
public void Draw()
{
CDraw.DrawTexture(CTheme.GetSkinTexture(_TextureName), _Rect, new SColorF(_Color.R, _Color.G, _Color.B, _Color.A * Alpha2 * _Alpha));
}
}
class CParticleEffect
{
private List<CParticle> _Stars;
private string _TextureName;
private int _MaxNumber;
private SRectF _Area;
private SColorF _Color;
private float _Size;
private EParticeType _Type;
private Stopwatch _SpawnTimer;
private float _NextSpawnTime;
public float Alpha = 1f;
public bool IsAlive
{
get
{
return (_Stars.Count > 0 || !_SpawnTimer.IsRunning);
}
}
public CParticleEffect(int MaxNumber, SColorF Color, SRectF Area, string TextureName, float Size, EParticeType Type)
{
_Stars = new List<CParticle>();
_Area = Area;
_Color = Color;
_TextureName = TextureName;
_MaxNumber = MaxNumber;
_Size = Size;
_Type = Type;
_SpawnTimer = new Stopwatch();
_NextSpawnTime = 0f;
}
public void Update()
{
bool DoSpawn = false;
if (!_SpawnTimer.IsRunning)
{
_SpawnTimer.Start();
_NextSpawnTime = 0f;
DoSpawn = true;
}
if (_SpawnTimer.ElapsedMilliseconds / 1000f > _NextSpawnTime && _NextSpawnTime >= 0f)
{
DoSpawn = true;
_SpawnTimer.Reset();
_SpawnTimer.Start();
}
while (_Stars.Count < _MaxNumber && DoSpawn)
{
float size = CGame.Rand.Next((int)_Size / 2) + _Size / 2;
float lifetime = 0f;
float vx = 0f;
float vy = 0f;
float vr = 0f;
float vsize = 0f;
_NextSpawnTime = 0f;
switch (_Type)
{
case EParticeType.Twinkle:
size = CGame.Rand.Next((int)_Size / 2) + _Size / 2;
lifetime = CGame.Rand.Next(500) / 1000f + 0.5f;
vx = -CGame.Rand.Next(10000) / 50f + 100f;
vy = -CGame.Rand.Next(10000) / 50f + 100f;
vr = -CGame.Rand.Next(500) / 100f + 2.5f;
vsize = lifetime * 2f;
break;
case EParticeType.Star:
size = CGame.Rand.Next((int)_Size / 2) + _Size / 2;
lifetime = CGame.Rand.Next(1000) / 500f + 0.2f;
vx = -CGame.Rand.Next(1000) / 50f + 10f;
vy = -CGame.Rand.Next(1000) / 50f + 10f;
vr = -CGame.Rand.Next(500) / 100f + 2.5f;
vsize = lifetime * 2f;
break;
case EParticeType.Snow:
size = CGame.Rand.Next((int)_Size / 2) + _Size / 2;
lifetime = CGame.Rand.Next(5000) / 50f + 10f;
vx = -CGame.Rand.Next(1000) / 50f + 10f;
vy = CGame.Rand.Next(1000) / 50f + Math.Abs(vx) + 10f;
vr = -CGame.Rand.Next(200) / 50f + 2f;
vsize = lifetime * 2f;
_NextSpawnTime = lifetime / _MaxNumber;
DoSpawn = false;
break;
case EParticeType.Flare:
size = CGame.Rand.Next((int)_Size / 2) + _Size / 2;
lifetime = CGame.Rand.Next(500) / 1000f + 0.1f;
vx = -CGame.Rand.Next(2000) / 50f;
vy = -CGame.Rand.Next(2000) / 50f + 20f;
vr = -CGame.Rand.Next(2000) / 50f + 20f;
vsize = lifetime * 2f;
break;
case EParticeType.PerfNoteStar:
size = CGame.Rand.Next((int)_Size / 2) + _Size / 2;
lifetime = CGame.Rand.Next(1000) / 500f + 1.2f;
vx = 0f;
vy = 0f;
vr = CGame.Rand.Next(500) / 50f + 10f;
vsize = lifetime * 2f;
break;
default:
break;
}
int w = (int)(_Area.W - size / 4f);
int h = (int)(_Area.H - size / 4f);
if (w < 0)
w = 0;
if (h < 0)
h = 0;
CParticle star = new CParticle(_TextureName, _Color,
CGame.Rand.Next(w) + _Area.X - size / 4f,
CGame.Rand.Next(h) + _Area.Y - size / 4f,
size, lifetime, _Area.Z, vx, vy, vr, vsize, _Type);
_Stars.Add(star);
}
if (_Type == EParticeType.Flare || _Type == EParticeType.PerfNoteStar || _Type == EParticeType.Twinkle)
_NextSpawnTime = -1f;
int i = 0;
while (i < _Stars.Count)
{
_Stars[i].Update();
if (!_Stars[i].IsAlive)
{
_Stars.RemoveAt(i);
}
else
i++;
}
}
public void Pause()
{
foreach (CParticle star in _Stars)
{
star.Pause();
}
}
public void Resume()
{
foreach (CParticle star in _Stars)
{
star.Resume();
}
}
public void Draw()
{
foreach (CParticle star in _Stars)
{
star.Alpha2 = Alpha;
star.Draw();
}
}
}
}
+756
View File
@@ -0,0 +1,756 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Base
{
public enum EAlignment
{
Left,
Center,
Right
}
public enum EStyle
{
Normal,
Italic,
Bold,
BoldItalic
}
class CGlyph
{
public readonly float SIZEh = 100f;
public STexture Texture;
public char Chr;
public int width;
public CGlyph(char chr)
{
TextFormatFlags flags = TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix;
float factor = GetFactor(chr, flags);
CFonts.Height = SIZEh * factor;
Bitmap bmp = new Bitmap(10, 10);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
Font fo = CFonts.GetFont();
Size sizeB = TextRenderer.MeasureText(g, chr.ToString(), fo, new Size(int.MaxValue, int.MaxValue), flags);
SizeF size = g.MeasureString(chr.ToString(), fo);
g.Dispose();
bmp.Dispose();
bmp = new Bitmap((int)(sizeB.Width * 1.5f), sizeB.Height);
g = System.Drawing.Graphics.FromImage(bmp);
g.Clear(System.Drawing.Color.Transparent);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
CFonts.Height = SIZEh;
fo = CFonts.GetFont();
g.DrawString(chr.ToString(), fo, Brushes.White, new PointF((sizeB.Width - size.Width) / 2f, (sizeB.Height - size.Height - (size.Height + SIZEh/4f) * (1f - factor)) / 2f));
Texture = CDraw.AddTexture(bmp);
Chr = chr;
width = (int)(sizeB.Width * Texture.width/factor / bmp.Width);
bmp.Dispose();
g.Dispose();
fo.Dispose();
}
private float GetFactor(char chr, TextFormatFlags flags)
{
if (CFonts.Style == EStyle.Normal)
return 1f;
EStyle style = CFonts.Style;
CFonts.Style = EStyle.Normal;
CFonts.Height = SIZEh;
Bitmap bmp = new Bitmap(10, 10);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
Font fo = CFonts.GetFont();
Size sizeB = TextRenderer.MeasureText(g, chr.ToString(), fo, new Size(int.MaxValue, int.MaxValue), flags);
//SizeF size = g.MeasureString(chr.ToString(), fo);
float h_normal = sizeB.Height;
CFonts.Style = style;
bmp = new Bitmap(10, 10);
g = System.Drawing.Graphics.FromImage(bmp);
fo = CFonts.GetFont();
sizeB = TextRenderer.MeasureText(g, chr.ToString(), fo, new Size(int.MaxValue, int.MaxValue), flags);
//size = g.MeasureString(chr.ToString(), fo);
float h_style = sizeB.Height;
return h_normal / h_style;
}
}
class CFont
{
private List<CGlyph> _Glyphs;
private Hashtable _htGlyphs;
private PrivateFontCollection fonts;
private FontFamily family;
public string FilePath;
public Font GetFont()
{
if (fonts == null)
{
fonts = new PrivateFontCollection();
try
{
fonts.AddFontFile(FilePath);
family = fonts.Families[0];
}
catch (Exception e)
{
CLog.LogError("Error opening font file " + FilePath + ": " + e.Message);
}
}
return new Font(family, CFonts.Height, CFonts.GetFontStyle(), GraphicsUnit.Pixel);
}
public CFont(string File)
{
FilePath = File;
_Glyphs = new List<CGlyph>();
_htGlyphs = new Hashtable();
}
public void DrawGlyph(char chr, float x, float y, float h, float z, SColorF color)
{
AddGlyph(chr);
CFonts.Height = h;
CGlyph glyph = _Glyphs[(int)_htGlyphs[chr]];
float factor = h / glyph.Texture.height;
CDraw.DrawTexture(glyph.Texture, new SRectF(x, y, glyph.Texture.width * factor, h, z), color);
}
public void DrawGlyphReflection(char chr, float x, float y, float h, float z, SColorF color, float rspace, float rheight)
{
AddGlyph(chr);
CFonts.Height = h;
CGlyph glyph = _Glyphs[(int)_htGlyphs[chr]];
float factor = h / glyph.Texture.height;
SRectF rect = new SRectF(x, y, glyph.Texture.width * factor, h, z);
CDraw.DrawTextureReflection(glyph.Texture, rect, color, rect, rspace, rheight);
}
public void DrawGlyph(char chr, float x, float y, float h, float z, SColorF color, float begin, float end)
{
AddGlyph(chr);
CFonts.Height = h;
CGlyph glyph = _Glyphs[(int)_htGlyphs[chr]];
float factor = h / glyph.Texture.height;
float width = glyph.Texture.width * factor;
CDraw.DrawTexture(glyph.Texture, new SRectF(x, y, width, h, z), color, begin, end);
}
public float GetWidth(char chr)
{
AddGlyph(chr);
CGlyph glyph = _Glyphs[(int)_htGlyphs[chr]];
float factor = CFonts.Height / glyph.Texture.height;
return glyph.width * factor;
}
public float GetHeight(char chr)
{
AddGlyph(chr);
CGlyph glyph = _Glyphs[(int)_htGlyphs[chr]];
float factor = CFonts.Height / glyph.Texture.height;
return glyph.Texture.height * factor;
}
public void AddGlyph(char chr)
{
if (_htGlyphs.ContainsKey(chr))
return;
float h = CFonts.Height;
_Glyphs.Add(new CGlyph(chr));
_htGlyphs.Add(chr, _Glyphs.Count - 1);
CFonts.Height = h;
}
}
struct SFont
{
public string Name;
public bool IsThemeFont;
public string ThemeName;
public string Folder;
public string FileNormal;
public string FileItalic;
public string FileBold;
public string FileBoldItalic;
public CFont Normal;
public CFont Italic;
public CFont Bold;
public CFont BoldItalic;
}
static class CFonts
{
private static XmlWriterSettings _settings = new XmlWriterSettings();
private static List<SFont> _Fonts;
private static int _CurrentFont;
private static float _Height = 1f;
public static EStyle Style = EStyle.Normal;
public static int CurrentFont
{
get { return _CurrentFont; }
set
{
if ((value >= 0) && (value < _Fonts.Count))
_CurrentFont = value;
}
}
public static float Height
{
get { return _Height; }
set
{
if (value < 0f)
_Height = 0f;
else
_Height = value;
}
}
public static void Init()
{
_settings.Indent = true;
_settings.Encoding = System.Text.Encoding.UTF8;
_settings.ConformanceLevel = ConformanceLevel.Document;
_CurrentFont = 0;
BuildFonts();
}
public static void BuildFonts()
{
_Fonts = new List<SFont>();
_CurrentFont = 0;
LoadFontList();
}
public static Font GetFont()
{
switch (Style)
{
case EStyle.Normal:
return _Fonts[_CurrentFont].Normal.GetFont();
case EStyle.Italic:
return _Fonts[_CurrentFont].Italic.GetFont();
case EStyle.Bold:
return _Fonts[_CurrentFont].Bold.GetFont();
case EStyle.BoldItalic:
return _Fonts[_CurrentFont].BoldItalic.GetFont();
default:
break;
}
// should never happen...
return null;
}
#region DrawText
public static void DrawText(string Text, int x, int y, int h)
{
DrawText(Text, h, x, y, 0f, new SColorF(0f, 0f, 0f, 1f));
}
public static void DrawText(string Text, float x, float y, float z)
{
DrawText(Text, Height, x, y, z, new SColorF(0f, 0f, 0f, 1f));
}
public static void DrawText(string Text, float h, float x, float y, float z, SColorF color)
{
if (h <= 0f)
return;
if (Text == String.Empty)
return;
Height = h;
float dx = x;
foreach (char chr in Text)
{
switch (Style)
{
case EStyle.Normal:
_Fonts[_CurrentFont].Normal.DrawGlyph(chr, dx, y, Height, z, color);
dx += _Fonts[_CurrentFont].Normal.GetWidth(chr);
break;
case EStyle.Italic:
_Fonts[_CurrentFont].Italic.DrawGlyph(chr, dx, y, Height, z, color);
dx += _Fonts[_CurrentFont].Italic.GetWidth(chr);
break;
case EStyle.Bold:
_Fonts[_CurrentFont].Bold.DrawGlyph(chr, dx, y, Height, z, color);
dx += _Fonts[_CurrentFont].Bold.GetWidth(chr);
break;
case EStyle.BoldItalic:
_Fonts[_CurrentFont].BoldItalic.DrawGlyph(chr, dx, y, Height, z, color);
dx += _Fonts[_CurrentFont].BoldItalic.GetWidth(chr);
break;
default:
break;
}
}
}
public static void DrawTextReflection(string Text, float h, float x, float y, float z, SColorF color, float rspace, float rheight)
{
if (h <= 0f)
return;
if (Text == String.Empty)
return;
Height = h;
float dx = x;
foreach (char chr in Text)
{
switch (Style)
{
case EStyle.Normal:
_Fonts[_CurrentFont].Normal.DrawGlyphReflection(chr, dx, y, Height, z, color, rspace, rheight);
dx += _Fonts[_CurrentFont].Normal.GetWidth(chr);
break;
case EStyle.Italic:
_Fonts[_CurrentFont].Italic.DrawGlyphReflection(chr, dx, y, Height, z, color, rspace, rheight);
dx += _Fonts[_CurrentFont].Italic.GetWidth(chr);
break;
case EStyle.Bold:
_Fonts[_CurrentFont].Bold.DrawGlyphReflection(chr, dx, y, Height, z, color, rspace, rheight);
dx += _Fonts[_CurrentFont].Bold.GetWidth(chr);
break;
case EStyle.BoldItalic:
_Fonts[_CurrentFont].BoldItalic.DrawGlyphReflection(chr, dx, y, Height, z, color, rspace, rheight);
dx += _Fonts[_CurrentFont].BoldItalic.GetWidth(chr);
break;
default:
break;
}
}
}
public static void DrawText(string Text, float h, float x, float y, float z, SColorF color, float begin, float end)
{
if (h <= 0f)
return;
if (Text == String.Empty)
return;
Height = h;
float dx = x;
float w = GetTextWidth(Text);
if (w <= 0f)
return;
float x1 = x + w * begin;
float x2 = x + w * end;
foreach (char chr in Text)
{
float w2 = 0f;
switch (Style)
{
case EStyle.Normal:
w2 = _Fonts[_CurrentFont].Normal.GetWidth(chr);
break;
case EStyle.Italic:
w2 = _Fonts[_CurrentFont].Italic.GetWidth(chr);
break;
case EStyle.Bold:
w2 = _Fonts[_CurrentFont].Bold.GetWidth(chr);
break;
case EStyle.BoldItalic:
w2 = _Fonts[_CurrentFont].BoldItalic.GetWidth(chr);
break;
default:
break;
}
float b = (x1 - dx) / w2;
if (b < 0f)
b = 0f;
if (b < 1f)
{
float e = (x2 - dx) / w2;
if (e > 1f)
e = 1f;
if (e > 0f)
{
switch (Style)
{
case EStyle.Normal:
_Fonts[_CurrentFont].Normal.DrawGlyph(chr, dx, y, Height, z, color, b, e);
break;
case EStyle.Italic:
_Fonts[_CurrentFont].Italic.DrawGlyph(chr, dx, y, Height, z, color, b, e);
break;
case EStyle.Bold:
_Fonts[_CurrentFont].Bold.DrawGlyph(chr, dx, y, Height, z, color, b, e);
break;
case EStyle.BoldItalic:
_Fonts[_CurrentFont].BoldItalic.DrawGlyph(chr, dx, y, Height, z, color, b, e);
break;
default:
break;
}
}
}
dx += w2;
}
}
#endregion DrawText
public static FontStyle GetFontStyle()
{
switch (Style)
{
case EStyle.Normal:
return FontStyle.Regular;
case EStyle.Italic:
return FontStyle.Italic;
case EStyle.Bold:
return FontStyle.Bold;
case EStyle.BoldItalic:
return FontStyle.Bold | FontStyle.Italic;
default:
return FontStyle.Regular;
}
}
public static void SetFont(string FontName)
{
int Index = GetFontIndex(CConfig.Theme, FontName);
if (Index >= 0 && Index < _Fonts.Count)
{
_CurrentFont = Index;
return;
}
for (int i = 0; i < _Fonts.Count; i++)
{
if (!_Fonts[i].IsThemeFont && _Fonts[i].Name == FontName)
{
_CurrentFont = i;
return;
}
}
}
public static float GetTextWidth(string text)
{
float dx = 0;
foreach (char chr in text)
{
switch (Style)
{
case EStyle.Normal:
dx += _Fonts[_CurrentFont].Normal.GetWidth(chr);
break;
case EStyle.Italic:
dx += _Fonts[_CurrentFont].Italic.GetWidth(chr);
break;
case EStyle.Bold:
dx += _Fonts[_CurrentFont].Bold.GetWidth(chr);
break;
case EStyle.BoldItalic:
dx += _Fonts[_CurrentFont].BoldItalic.GetWidth(chr);
break;
default:
break;
}
}
return dx;
}
public static float GetTextHeight(string text)
{
//return TextRenderer.MeasureText(text, GetFont()).Height;
float h = 0f;
foreach (char chr in text)
{
float hh = 0f;
switch (Style)
{
case EStyle.Normal:
hh = _Fonts[_CurrentFont].Normal.GetHeight(chr);
break;
case EStyle.Italic:
hh = _Fonts[_CurrentFont].Italic.GetHeight(chr);
break;
case EStyle.Bold:
hh = _Fonts[_CurrentFont].Bold.GetHeight(chr);
break;
case EStyle.BoldItalic:
hh = _Fonts[_CurrentFont].BoldItalic.GetHeight(chr);
break;
default:
break;
}
if (hh>h)
h = hh;
}
return h;
}
/// <summary>
/// Load default fonts
/// </summary>
/// <returns></returns>
private static bool LoadFontList()
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(System.IO.Path.Combine(CSettings.sFolderFonts, CSettings.sFileFonts));
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception e)
{
CLog.LogError("Error loading default fonts: " + e.Message);
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
_Fonts.Clear();
if (loaded)
{
string value = string.Empty;
int i = 1;
while (CHelper.GetValueFromXML("//root/Font" + i.ToString() + "/Folder", navigator, ref value, value))
{
string Folder = value;
CHelper.GetValueFromXML("//root/Font" + i.ToString() + "/FileNormal", navigator, ref value, value);
value = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(CSettings.sFolderFonts, Path.Combine(Folder, value)));
CFont f = new CFont(value);
SFont sf = new SFont();
sf.Normal = f;
string name = String.Empty;
CHelper.GetValueFromXML("//root/Font" + i.ToString() + "/Name", navigator, ref name, value);
sf.Name = name;
sf.IsThemeFont = false;
sf.ThemeName = String.Empty;
CHelper.GetValueFromXML("//root/Font" + i.ToString() + "/FileItalic", navigator, ref value, value);
value = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(CSettings.sFolderFonts, Path.Combine(Folder, value)));
f = new CFont(value);
sf.Italic = f;
CHelper.GetValueFromXML("//root/Font" + i.ToString() + "/FileBold", navigator, ref value, value);
value = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(CSettings.sFolderFonts, Path.Combine(Folder, value)));
f = new CFont(value);
sf.Bold = f;
CHelper.GetValueFromXML("//root/Font" + i.ToString() + "/FileBoldItalic", navigator, ref value, value);
value = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(CSettings.sFolderFonts, Path.Combine(Folder, value)));
f = new CFont(value);
sf.BoldItalic = f;
_Fonts.Add(sf);
i++;
}
}
return loaded;
}
/// <summary>
/// Loads theme fonts from skin file
/// </summary>
public static void LoadThemeFonts(string ThemeName, string SkinFolder, XPathNavigator navigator)
{
string value = string.Empty;
int i = 1;
while (CHelper.GetValueFromXML("//root/Fonts/Font" + i.ToString() + "/Folder", navigator, ref value, value))
{
SFont sf = new SFont();
sf.Folder = value;
sf.IsThemeFont = true;
sf.ThemeName = ThemeName;
bool ok = true;
ok &= CHelper.GetValueFromXML("//root/Fonts/Font" + i.ToString() + "/FileNormal", navigator, ref value, value);
sf.FileNormal = value;
value = Path.Combine(SkinFolder, Path.Combine(sf.Folder, value));
CFont f = new CFont(value);
sf.Normal = f;
string name = String.Empty;
ok &= CHelper.GetValueFromXML("//root/Fonts/Font" + i.ToString() + "/Name", navigator, ref name, value);
sf.Name = name;
ok &= CHelper.GetValueFromXML("//root/Fonts/Font" + i.ToString() + "/FileItalic", navigator, ref value, value);
sf.FileItalic = value;
value = Path.Combine(SkinFolder, Path.Combine(sf.Folder, value));
f = new CFont(value);
sf.Italic = f;
ok &= CHelper.GetValueFromXML("//root/Fonts/Font" + i.ToString() + "/FileBold", navigator, ref value, value);
sf.FileBold = value;
value = Path.Combine(SkinFolder, Path.Combine(sf.Folder, value));
f = new CFont(value);
sf.Bold = f;
ok &= CHelper.GetValueFromXML("//root/Fonts/Font" + i.ToString() + "/FileBoldItalic", navigator, ref value, value);
sf.FileBoldItalic = value;
value = Path.Combine(SkinFolder, Path.Combine(sf.Folder, value));
f = new CFont(value);
sf.BoldItalic = f;
if (ok)
_Fonts.Add(sf);
else
{
CLog.LogError("Error loading theme fonts for theme \"" + ThemeName + "\": Error in Font" + i.ToString());
}
i++;
}
CLog.StartBenchmark(1, "BuildGlyphs");
BuildGlyphs();
CLog.StopBenchmark(1, "BuildGlyphs");
}
public static void SaveThemeFonts(string ThemeName, XmlWriter writer)
{
if (_Fonts.Count == 0)
return;
int Index = 0;
int FontNr = 1;
bool SetStart = false;
while (Index < _Fonts.Count)
{
if (_Fonts[Index].IsThemeFont && _Fonts[Index].ThemeName == ThemeName)
{
if (!SetStart)
{
writer.WriteStartElement("Fonts");
SetStart = true;
}
writer.WriteStartElement("Font" + FontNr.ToString());
writer.WriteElementString("Name", _Fonts[Index].Name);
writer.WriteElementString("Folder", _Fonts[Index].Folder);
writer.WriteElementString("FileNormal", _Fonts[Index].FileNormal);
writer.WriteElementString("FileBold", _Fonts[Index].FileBold);
writer.WriteElementString("FileItalic", _Fonts[Index].FileItalic);
writer.WriteElementString("FileBoldItalic", _Fonts[Index].FileBoldItalic);
writer.WriteEndElement();
FontNr++;
}
Index++;
}
if (SetStart)
writer.WriteEndElement();
}
private static int GetFontIndex(string ThemeName, string FontName)
{
if (ThemeName == String.Empty || FontName == String.Empty)
return -1;
for (int i = 0; i < _Fonts.Count; i++)
{
if (_Fonts[i].IsThemeFont && _Fonts[i].Name == FontName && _Fonts[i].ThemeName == ThemeName)
return i;
}
return -1;
}
private static void BuildGlyphs()
{
string Text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPGRSTUVWGXZ1234567890";
for (int i = 0; i < _Fonts.Count; i++)
{
CurrentFont = i;
foreach (char chr in Text)
{
Style = EStyle.Normal;
_Fonts[_CurrentFont].Normal.AddGlyph(chr);
Style = EStyle.Bold;
_Fonts[_CurrentFont].Bold.AddGlyph(chr);
Style = EStyle.Italic;
_Fonts[_CurrentFont].Italic.AddGlyph(chr);
Style = EStyle.BoldItalic;
_Fonts[_CurrentFont].BoldItalic.AddGlyph(chr);
}
}
Style = EStyle.Normal;
SetFont("Normal");
}
}
}
+393
View File
@@ -0,0 +1,393 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Vocaluxe.GameModes;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Song;
namespace Vocaluxe.Base
{
struct SPlayer
{
public int ProfileID;
public string Name;
public EGameDifficulty Difficulty;
public double Points;
public int NoteDiff;
public int LineNr;
public List<CLine> SingLine;
public int CurrentLine;
public int CurrentNote;
public int SongID;
public bool Medley;
public bool Duet;
public long DateTicks;
public bool SongFinished;
}
struct SScores
{
public string Name;
public int Score;
public string Date;
public EGameDifficulty Difficulty;
public int LineNr;
public int ID;
}
static class CGame
{
private static IGameMode _GameMode;
private static SPlayer[] _Player;
private static int _NumPlayer = CConfig.NumPlayer;
private static float _Beat = 0f;
private static int _CurrentBeat = 0;
private static float _MidBeatD = 0f;
private static int _CurrentBeatD = 0;
private static int _OldBeatD = 0;
private static Random _Rand = new Random();
public static Random Rand
{
get { return _Rand; }
}
public static float GetBeatFromTime(float Time, float BPM, float Gap)
{
return BPM / 60 * (Time - Gap);
}
public static float GetTimeFromBeats(float Beats, float BPM)
{
if (BPM > 0f)
return Beats / BPM * 60f;
return 0f;
}
public static int CurrentBeat
{
get { return _CurrentBeat; }
}
public static float Beat
{
get { return _Beat; }
}
public static float MidBeatD
{
get { return _MidBeatD; }
}
public static int ActBeatD
{
get { return _CurrentBeatD; }
}
public static SPlayer[] Player
{
get { return _Player; }
}
public static void Init()
{
_GameMode = new CGameModeNormal();
_GameMode.Init();
_Player = new SPlayer[CSettings.MaxNumPlayer];
ResetPlayer();
}
public static void SetGameMode(EGameMode Mode)
{
switch (Mode)
{
case EGameMode.Normal:
_GameMode = new CGameModeNormal();
break;
case EGameMode.Medley:
_GameMode = new CGameModeMedley();
break;
case EGameMode.Duet:
_GameMode = new CGameModeDuet();
break;
default:
break;
}
_GameMode.Init();
}
public static EGameMode GameMode
{
get { return _GameMode.GetGameMode(); }
}
public static bool AddVisibleSong(int VisibleIndex)
{
return _GameMode.AddVisibleSong(VisibleIndex);
}
public static bool AddSong(int AbsoluteIndex)
{
return _GameMode.AddSong(AbsoluteIndex);
}
public static bool RemoveVisibleSong(int VisibleIndex)
{
return _GameMode.RemoveVisibleSong(VisibleIndex);
}
public static bool RemoveSong(int AbsoluteIndex)
{
return _GameMode.RemoveSong(AbsoluteIndex);
}
public static void ClearSongs()
{
_GameMode.ClearSongs();
}
public static void Reset()
{
_GameMode.Reset();
}
public static void Start()
{
_GameMode.Start(_Player);
}
public static void NextRound()
{
_GameMode.NextRound(_Player);
}
public static bool IsFinished()
{
return _GameMode.IsFinished();
}
public static int RoundNr
{
get { return _GameMode.GetActualRoundNr(); }
}
public static CSong GetSong()
{
return _GameMode.GetSong();
}
public static CSong GetSong(int Num)
{
return _GameMode.GetSong(Num);
}
public static int GetNumSongs()
{
return _GameMode.GetNumSongs();
}
public static CPoints GetPoints()
{
return _GameMode.GetPoints();
}
public static int NumPlayer
{
get { return _NumPlayer; }
set
{
if (value > 0 && value <= CSettings.MaxNumPlayer)
_NumPlayer = value;
}
}
public static void ResetPlayer()
{
for (int i = 0; i < _Player.Length; i++)
{
_Player[i].Points = 0f;
_Player[i].LineNr = 0;
_Player[i].NoteDiff = 0;
_Player[i].SingLine = new List<CLine>();
_Player[i].CurrentLine = -1;
_Player[i].CurrentNote = -1;
_Player[i].SongID = -1;
_Player[i].Medley = false;
_Player[i].Duet = false;
_Player[i].DateTicks = DateTime.Now.Ticks;
_Player[i].SongFinished = false;
}
_OldBeatD = -100;
}
public static void UpdatePoints(float Time)
{
const bool DEBUG_HIT = false;
CSong song = _GameMode.GetSong();
if (song == null)
return;
_Beat = GetBeatFromTime(Time, song.BPM, song.Gap);
_CurrentBeat = (int)Math.Floor(_Beat);
_MidBeatD = -0.5f + GetBeatFromTime(Time, song.BPM, song.Gap + CConfig.MicDelay/1000f);
_CurrentBeatD = (int)Math.Floor(_MidBeatD);
if (_OldBeatD == _CurrentBeatD)
return;
for (int p = 0; p < _NumPlayer; p++)
{
CSound.AnalyzeBuffer(p);
if (CSound.RecordToneValid(p) || DEBUG_HIT)
{
for (int beat = _OldBeatD + 1; beat <= _CurrentBeatD; beat++)
{
CLine[] lines = song.Notes.GetLines(_Player[p].LineNr).Line;
int Line = -1;
for (int j = 0; j < lines.Length; j++)
{
if (beat >= lines[j].StartBeat && beat <= lines[j].EndBeat)
{
Line = j;
break;
}
}
if (Line >= 0)
{
if (Line != _Player[p].CurrentLine)
_Player[p].CurrentNote = -1;
_Player[p].CurrentLine = Line;
while (_Player[p].SingLine.Count <= Line)
{
_Player[p].SingLine.Add(new CLine());
}
CNote[] notes = lines[Line].Notes;
int Note = -1;
for (int j = 0; j < notes.Length; j++)
{
if (beat >= notes[j].StartBeat && beat <= notes[j].EndBeat)
{
if (notes[j].PointsForBeat > 0)
Note = j;
break;
}
}
if (Note >= 0)
{
if (Line == lines.Length - 1)
{
if (Note == lines[Line].NoteCount - 1)
{
_Player[p].SongFinished = true;
}
}
}
if (Note >= 0 && notes[Note].PointsForBeat > 0)
{
_Player[p].CurrentNote = Note;
if (Line == lines.Length - 1)
{
if (Note == lines[Line].NoteCount - 1)
{
if (notes[Note].EndBeat == beat)
_Player[p].SongFinished = true;
}
}
int Tone = notes[Note].Tone;
int TonePlayer = CSound.RecordGetTone(p);
while (TonePlayer - Tone > 6)
TonePlayer -= 12;
while (TonePlayer - Tone < -6)
TonePlayer += 12;
if (DEBUG_HIT)
TonePlayer = Tone;
_Player[p].NoteDiff = Math.Abs(Tone - TonePlayer);
if (_Player[p].NoteDiff <= (2 - (int)_Player[p].Difficulty))
{
// valid
CSound.RecordSetTone(p, Tone);
_Player[p].Points += (CSettings.MaxScore - CSettings.LinebonusScore) * (double)notes[Note].PointsForBeat / (double)song.Notes.GetLines(_Player[p].LineNr).Points;
// update player notes (sung notes)
if (_Player[p].SingLine[Line].NoteCount > 0)
{
CNote nt = _Player[p].SingLine[Line].LastNote;
if (notes[Note].StartBeat == beat || nt.EndBeat + 1 != beat || nt.Tone != Tone)
_Player[p].SingLine[Line].AddNote(new CNote(beat, 1, Tone, String.Empty, true, notes[Note].NoteType));
else
{
_Player[p].SingLine[Line].IncLastNoteLength();
}
}
else
{
_Player[p].SingLine[Line].AddNote(new CNote(beat, 1, Tone, String.Empty, true, notes[Note].NoteType));
}
_Player[p].SingLine[Line].LastNote.IsPerfect(notes[Note]);
_Player[p].SingLine[Line].IsPerfect(lines[Line]);
if (_Player[p].SingLine[Line].PerfectLine)
{
_Player[p].Points += CSettings.LinebonusScore * (double)lines[Line].Points / (double)song.Notes.GetPoints(_Player[p].LineNr);
}
}
else
{
if (_Player[p].SingLine[Line].NoteCount > 0)
{
CNote nt = _Player[p].SingLine[Line].LastNote;
if (nt.EndBeat + 1 != beat || nt.Hit)
_Player[p].SingLine[Line].AddNote(new CNote(beat, 1, TonePlayer, String.Empty, false, notes[Note].NoteType));
else
{
if (nt.Tone == TonePlayer && nt.EndBeat + 1 == beat)
{
_Player[p].SingLine[Line].IncLastNoteLength();
}
else
{
_Player[p].SingLine[Line].AddNote(new CNote(beat, 1, TonePlayer, String.Empty, false, notes[Note].NoteType));
}
}
}
else
{
_Player[p].SingLine[Line].AddNote(new CNote(beat, 1, TonePlayer, String.Empty, false, notes[Note].NoteType));
}
}
}
}
}
}
}
_OldBeatD = _CurrentBeatD;
}
}
}
+214
View File
@@ -0,0 +1,214 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace Vocaluxe.Base
{
struct SLanguage
{
public string Name;
public string LanguageFilePath;
public Hashtable Texts;
}
static class CLanguage
{
private static XmlWriterSettings _settings = new XmlWriterSettings();
private static List<SLanguage> _Languages;
private static CHelper Helper = new CHelper();
private static int _CurrentLanguage = 0;
private static int _FallbackLanguage = 0;
public static int Language
{
get { return _CurrentLanguage; }
set
{
if (value >= 0 && value < _Languages.Count)
_CurrentLanguage = value;
}
}
public static List<string> GetLanguages()
{
List<string> Languages = new List<string>();
for (int i = 0; i < _Languages.Count; i++)
{
Languages.Add(_Languages[i].Name);
}
return Languages;
}
public static void Init()
{
_Languages = new List<SLanguage>();
_settings.Indent = true;
_settings.Encoding = System.Text.Encoding.UTF8;
_settings.ConformanceLevel = ConformanceLevel.Document;
List<string> files = new List<string>();
files.AddRange(Helper.ListFiles(CSettings.sFolderLanguages, "*.xml", true, true));
foreach (string file in files)
{
LoadLanguageFile(file);
}
}
public static bool SetLanguage(string Language)
{
for (int i = 0; i < _Languages.Count; i++)
{
if (_Languages[i].Name == Language)
{
_CurrentLanguage = i;
return true;
}
}
return false;
}
public static string Translate(string KeyWord)
{
if (KeyWord.Length < 3)
return KeyWord;
string tag = KeyWord.Substring(0, 3);
if (tag != "TR_")
return KeyWord;
string result = String.Empty;
try
{
result = (string)_Languages[_CurrentLanguage].Texts[KeyWord];
}
catch (Exception)
{
;
}
if (result == null)
{
// keyword not found, try fallback-language
try
{
result = (string)_Languages[_FallbackLanguage].Texts[KeyWord];
}
catch (Exception)
{
;
}
if (result == null)
return KeyWord;
}
return result;
}
public static bool TranslationExists(string KeyWord)
{
if (KeyWord.Length < 3)
return false;
string tag = KeyWord.Substring(0, 3);
if (tag != "TR_")
return false;
string result = String.Empty;
try
{
result = (string)_Languages[_CurrentLanguage].Texts[KeyWord];
}
catch (Exception)
{
;
}
if (result == null)
{
// keyword not found, try fallback-language
try
{
result = (string)_Languages[_FallbackLanguage].Texts[KeyWord];
}
catch (Exception)
{
;
}
if (result == null)
return false;
}
return true;
}
private static void LoadLanguageFile(string FileName)
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
SLanguage lang = new SLanguage();
lang.LanguageFilePath = Path.Combine(CSettings.sFolderLanguages, FileName);
try
{
xPathDoc = new XPathDocument(lang.LanguageFilePath);
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception e)
{
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
CLog.LogError("Error opening Language File " + FileName + ": " + e.Message);
}
if (loaded)
{
string value = string.Empty;
if (CHelper.GetValueFromXML("//root/Info/Name", navigator, ref value, value))
{
lang.Name = value;
if (lang.Name == CSettings.FallbackLanguage)
_FallbackLanguage = _Languages.Count;
lang.Texts = new Hashtable();
List<string> texts = CHelper.GetValuesFromXML("Texts", navigator);
for (int i = 0; i < texts.Count; i++)
{
if (CHelper.GetValueFromXML("//root/Texts/" + texts[i], navigator, ref value, value))
{
try
{
lang.Texts.Add(texts[i], value);
}
catch (Exception e)
{
CLog.LogError("Error reading Language File " + FileName + ": " + e.Message);
}
}
}
_Languages.Add(lang);
}
}
}
}
}
+143
View File
@@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Vocaluxe.Base
{
class Log
{
private string _LogFileName;
private string _LogName;
private StreamWriter _LogFile;
public Log(string FileName, string LogName)
{
_LogName = LogName;
_LogFileName = FileName;
}
public void Close()
{
if (_LogFile != null)
{
_LogFile.Flush();
_LogFile.Close();
}
}
public void Add(string Text)
{
if (_LogFile == null)
Open();
_LogFile.WriteLine(Text);
_LogFile.Flush();
}
private void Open()
{
_LogFile = new StreamWriter(Path.Combine(Environment.CurrentDirectory, _LogFileName), false, Encoding.UTF8);
_LogFile.WriteLine(_LogName + " " + CSettings.GetFullVersionText() + " " + DateTime.Now.ToString());
_LogFile.WriteLine("----------------------------------------");
_LogFile.WriteLine();
}
}
static class CLog
{
private const int MAXBenchmarks = 10;
private static Log _ErrorLog;
private static Log _PerformanceLog;
private static Log _BenchmarkLog;
private static int _NumErrors;
private static Stopwatch[] _BenchmarkTimer;
private static long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
public static void Init()
{
_ErrorLog = new Log(CSettings.sFileErrorLog, "ErrorLog");
_PerformanceLog = new Log(CSettings.sFilePerformanceLog, "PerformanceLog");
_BenchmarkLog = new Log(CSettings.sFileBenchmarkLog, "BenchmarkLog");
_NumErrors = 0;
_BenchmarkTimer = new Stopwatch[MAXBenchmarks];
for (int i = 0; i < _BenchmarkTimer.Length; i++)
{
_BenchmarkTimer[i] = new Stopwatch();
}
}
public static void CloseAll()
{
_ErrorLog.Close();
_PerformanceLog.Close();
_BenchmarkLog.Close();
}
#region LogError
public static void LogError(string ErrorText)
{
_NumErrors++;
_ErrorLog.Add(_NumErrors.ToString() + ") " + ErrorText);
_ErrorLog.Add(String.Empty);
}
#endregion LogError
#region LogPerformance
public static void LogPerformance(string Text)
{
_PerformanceLog.Add(Text);
_PerformanceLog.Add("-------------------------------");
}
#endregion LogPerformance
#region LogBenchmark
public static void StartBenchmark(int BenchmarkNr, string Text)
{
if (BenchmarkNr >= 0 && BenchmarkNr < MAXBenchmarks)
{
_BenchmarkTimer[BenchmarkNr].Stop();
_BenchmarkTimer[BenchmarkNr].Reset();
string space = String.Empty;
for (int i = 0; i < BenchmarkNr; i++)
{
space += " ";
}
_BenchmarkLog.Add(space + "Start " + Text);
_BenchmarkTimer[BenchmarkNr].Start();
}
}
public static void StopBenchmark(int BenchmarkNr, string Text)
{
if (BenchmarkNr >= 0 && BenchmarkNr < MAXBenchmarks)
{
_BenchmarkTimer[BenchmarkNr].Stop();
string space = String.Empty;
for (int i = 0; i < BenchmarkNr; i++)
{
space += " ";
}
float ms;
if (Stopwatch.IsHighResolution)
ms = (float)(((double)nanosecPerTick * (double)_BenchmarkTimer[BenchmarkNr].ElapsedTicks) / (1000.0 * 1000.0));
else
ms = (float)_BenchmarkTimer[BenchmarkNr].ElapsedMilliseconds;
_BenchmarkLog.Add(space + "Stop " + Text + ", Elapsed Time: " + ms.ToString("0.000") + "ms");
_BenchmarkLog.Add(String.Empty);
}
}
#endregion LogBenchmark
}
}
+441
View File
@@ -0,0 +1,441 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Base
{
struct SProfile
{
public string PlayerName;
public string ProfileFile;
public EGameDifficulty Difficulty;
public SAvatar Avatar;
public EOffOn GuestProfile;
public EOffOn Active;
}
struct SAvatar
{
public string FileName;
public STexture Texture;
public SAvatar(int dummy)
{
FileName = String.Empty;
Texture = new STexture(-1);
}
}
static class CProfiles
{
private static XmlWriterSettings _settings = new XmlWriterSettings();
private static CHelper Helper = new CHelper();
private static List<SProfile> _Profiles;
private static List<SAvatar> _Avatars = new List<SAvatar>();
public static SProfile[] Profiles
{
get { return _Profiles.ToArray(); }
}
public static int NumProfiles
{
get { return _Profiles.Count; }
}
public static SAvatar[] Avatars
{
get { return _Avatars.ToArray(); }
}
public static int NumAvatars
{
get { return _Avatars.Count; }
}
public static void Init()
{
_settings.Indent = true;
_settings.Encoding = System.Text.Encoding.UTF8;
_settings.ConformanceLevel = ConformanceLevel.Document;
LoadAvatars();
LoadProfiles();
}
public static int NewProfile()
{
return NewProfile(String.Empty);
}
public static int NewProfile(string FileName)
{
SProfile profile = new SProfile();
profile.PlayerName = String.Empty;
profile.Difficulty = EGameDifficulty.TR_CONFIG_EASY;
profile.Avatar = new SAvatar(-1);
profile.GuestProfile = EOffOn.TR_CONFIG_OFF;
profile.Active = EOffOn.TR_CONFIG_ON;
if (FileName != String.Empty)
profile.ProfileFile = Path.Combine(CSettings.sFolderProfiles, FileName);
else
profile.ProfileFile = String.Empty;
if (File.Exists(profile.ProfileFile))
return -1;
_Profiles.Add(profile);
return _Profiles.Count - 1;
}
public static void SaveProfiles()
{
for (int i = 0; i < _Profiles.Count; i++)
{
SaveProfile(i);
}
LoadProfiles();
}
public static void LoadProfiles()
{
_Profiles = new List<SProfile>();
List<string> files = new List<string>();
files.AddRange(Helper.ListFiles(CSettings.sFolderProfiles, "*.xml", true, true));
foreach (string file in files)
{
LoadProfile(file);
}
SortProfilesByName();
}
public static void LoadAvatars()
{
for (int i = 0; i < _Avatars.Count; i++)
{
STexture texture = _Avatars[i].Texture;
CDraw.RemoveTexture(ref texture);
}
_Avatars.Clear();
List<string> files = new List<string>();
files.AddRange(Helper.ListFiles(CSettings.sFolderProfiles, "*.png", true, true));
files.AddRange(Helper.ListFiles(CSettings.sFolderProfiles, "*.jpg", true, true));
files.AddRange(Helper.ListFiles(CSettings.sFolderProfiles, "*.jpeg", true, true));
files.AddRange(Helper.ListFiles(CSettings.sFolderProfiles, "*.bmp", true, true));
foreach (string file in files)
{
STexture tex = CDraw.AddTexture(file);
if (tex.index != -1)
{
SAvatar avatar = new SAvatar();
avatar.Texture = tex;
avatar.FileName = Path.GetFileName(file);
_Avatars.Add(avatar);
}
}
}
public static string AddGetPlayerName(int ProfileNr, char Chr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return String.Empty;
SProfile profile = _Profiles[ProfileNr];
profile.PlayerName += Chr;
_Profiles[ProfileNr] = profile;
return profile.PlayerName;
}
public static string GetPlayerName(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return String.Empty;
return _Profiles[ProfileNr].PlayerName;
}
public static string GetDeleteCharInPlayerName(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return String.Empty;
SProfile profile = _Profiles[ProfileNr];
if (profile.PlayerName.Length > 0)
profile.PlayerName = profile.PlayerName.Remove(profile.PlayerName.Length - 1);
_Profiles[ProfileNr] = profile;
return profile.PlayerName;
}
public static EGameDifficulty GetDifficulty(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return EGameDifficulty.TR_CONFIG_NORMAL;
return _Profiles[ProfileNr].Difficulty;
}
public static void SetDifficulty(int ProfileNr, EGameDifficulty Difficulty)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return;
SProfile profile = _Profiles[ProfileNr];
profile.Difficulty = Difficulty;
_Profiles[ProfileNr] = profile;
}
public static EOffOn GetGuestProfile(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return EOffOn.TR_CONFIG_OFF;
return _Profiles[ProfileNr].GuestProfile;
}
public static EOffOn GetActive(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return EOffOn.TR_CONFIG_OFF;
return _Profiles[ProfileNr].Active;
}
public static void SetGuestProfile(int ProfileNr, EOffOn Option)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return;
SProfile profile = _Profiles[ProfileNr];
profile.GuestProfile = Option;
_Profiles[ProfileNr] = profile;
}
public static void SetActive(int ProfileNr, EOffOn Option)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return;
SProfile profile = _Profiles[ProfileNr];
profile.Active = Option;
_Profiles[ProfileNr] = profile;
}
public static bool IsGuestProfile(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return false;
return _Profiles[ProfileNr].GuestProfile == EOffOn.TR_CONFIG_ON;
}
public static bool IsActive(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return false;
return _Profiles[ProfileNr].GuestProfile == EOffOn.TR_CONFIG_ON;
}
public static void SetAvatar(int ProfileNr, int AvatarNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count || AvatarNr < 0 || AvatarNr >= _Avatars.Count)
return;
SProfile profile = _Profiles[ProfileNr];
profile.Avatar = _Avatars[AvatarNr];
_Profiles[ProfileNr] = profile;
}
public static int GetAvatarNr(int ProfileNr)
{
if (ProfileNr < 0 || ProfileNr >= _Profiles.Count)
return 0;
for (int i = 0; i < _Avatars.Count; i++)
{
if (_Profiles[ProfileNr].Avatar.FileName == _Avatars[i].FileName)
return i;
}
return 0;
}
public static void DeleteProfile(int ProfileID)
{
if (ProfileID < 0 || ProfileID >= _Profiles.Count)
return;
if (_Profiles[ProfileID].ProfileFile != String.Empty)
{
try
{
File.Delete(_Profiles[ProfileID].ProfileFile);
_Profiles.RemoveAt(ProfileID);
}
catch (Exception)
{
CLog.LogError("Can't delete Profile File " + _Profiles[ProfileID].ProfileFile + ".xml");
}
}
}
private static void SortProfilesByName()
{
_Profiles.Sort(CompareByPlayerName);
}
private static int CompareByPlayerName(SProfile a, SProfile b)
{
return String.Compare(a.PlayerName, b.PlayerName);
}
#region private methods
private static SAvatar GetAvatar(string FileName)
{
foreach (SAvatar avatar in _Avatars)
{
if (FileName == avatar.FileName)
return avatar;
}
return new SAvatar(-1);
}
private static void SaveProfile(int ProfileID)
{
if (ProfileID < 0 || ProfileID >= _Profiles.Count)
return;
if (_Profiles[ProfileID].ProfileFile == String.Empty)
{
string filename = string.Empty;
foreach (char chr in _Profiles[ProfileID].PlayerName)
{
if (char.IsLetter(chr))
filename += chr.ToString();
}
if (filename == String.Empty)
filename = "1";
int i = 0;
while(File.Exists(Path.Combine(CSettings.sFolderProfiles, filename + ".xml")))
{
i++;
if(!File.Exists(Path.Combine(CSettings.sFolderProfiles, filename + i + ".xml")))
{
filename += i;
}
}
SProfile profile = _Profiles[ProfileID];
profile.ProfileFile = Path.Combine(CSettings.sFolderProfiles, filename + ".xml");
_Profiles[ProfileID] = profile;
}
XmlWriter writer;
try
{
writer = XmlWriter.Create(_Profiles[ProfileID].ProfileFile, _settings);
}
catch (Exception e)
{
CLog.LogError("Error creating/opening Profile File " + _Profiles[ProfileID].ProfileFile + ": " + e.Message);
return;
}
if (writer == null)
{
CLog.LogError("Error creating/opening Profile File " + _Profiles[ProfileID].ProfileFile);
return;
}
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteStartElement("Info");
writer.WriteElementString("PlayerName", _Profiles[ProfileID].PlayerName);
writer.WriteElementString("Difficulty", Enum.GetName(typeof(EGameDifficulty), _Profiles[ProfileID].Difficulty));
writer.WriteElementString("Avatar", _Profiles[ProfileID].Avatar.FileName);
writer.WriteElementString("GuestProfile", Enum.GetName(typeof(EOffOn), _Profiles[ProfileID].GuestProfile));
writer.WriteElementString("Active", Enum.GetName(typeof(EOffOn), _Profiles[ProfileID].Active));
writer.WriteEndElement();
writer.WriteEndElement(); //end of root
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
private static void LoadProfile(string FileName)
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
SProfile profile = new SProfile();
profile.ProfileFile = Path.Combine(CSettings.sFolderProfiles, FileName);
try
{
xPathDoc = new XPathDocument(profile.ProfileFile);
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception e)
{
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
CLog.LogError("Error opening Profile File " + FileName + ": " + e.Message);
}
if (loaded)
{
string value = String.Empty;
if (CHelper.GetValueFromXML("//root/Info/PlayerName", navigator, ref value, value))
{
profile.PlayerName = value;
profile.Difficulty = EGameDifficulty.TR_CONFIG_EASY;
CHelper.TryGetEnumValueFromXML<EGameDifficulty>("//root/Info/Difficulty", navigator, ref profile.Difficulty);
profile.Avatar = new SAvatar(-1);
if (CHelper.GetValueFromXML("//root/Info/Avatar", navigator, ref value, value))
{
profile.Avatar = GetAvatar(value);
}
profile.GuestProfile = EOffOn.TR_CONFIG_OFF;
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Info/GuestProfile", navigator, ref profile.GuestProfile);
profile.Active = EOffOn.TR_CONFIG_ON;
CHelper.TryGetEnumValueFromXML<EOffOn>("//root/Info/Active", navigator, ref profile.Active);
_Profiles.Add(profile);
}
else
{
CLog.LogError("Can't find PlayerName in Profile File: " + FileName);
}
}
}
#endregion private methods
}
}
+141
View File
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Base
{
public enum EGameState
{
Start,
Normal,
EditTheme
}
enum ERevision
{
Alpha,
Beta,
RC,
Release
}
static class CSettings
{
public static EGameState GameState = EGameState.Start;
public const string sProgramName = "Vocaluxe";
public const string sProgramCodeName = "Rising Star";
public const int iVersionMajor = 0;
public const int iVersionMinor = 1; // milestones
public const int iVersionSub = 0; // steps
public const ERevision VersionRevision = ERevision.Alpha;
public const int iBuild = 50; // Increase on every published version! Never Reset!
public const int iDatabaseHighscoreVersion = 1;
public const int iDatabaseCoverVersion = 1;
public static int iRenderW = 1280;
public static int iRenderH = 720;
public static int zNear = -100;
public static int zFar = 100;
public static bool bFullScreen = false;
public const string sIcon = "Vocaluxe.ico";
public const string FallbackLanguage = "English";
public static string sBassRegistration = "Registration.xml";
public static string sFileConfig = "Config.xml";
public const string sFileCover = "Cover.xml";
public const string sFileFonts = "Fonts.xml";
public static string sFileHighscoreDB = "HighscoreDB.sqlite";
public const string sFileCoverDB = "CoverDB.sqlite";
public const string sFilePerformanceLog = "Performance.log";
public const string sFileErrorLog = "Error.log";
public const string sFileBenchmarkLog = "Benchmark.log";
public const string sSoundT440 = "440Hz.mp3";
public const string sFolderCover = "Cover";
public const string sFolderFonts = "Fonts";
public const string sFolderThemes = "Themes";
public const string sFolderSkins = "Skins";
public const string sFolderThemeFonts = "Fonts";
public const string sFolderScreens = "Screens";
public const string sFolderProfiles = "Profiles";
public const string sFolderSongs = "Songs";
public const string sFolderSounds = "Sounds";
public const string sFolderLanguages = "Languages";
public const string sFolderScreenshots = "Screenshots";
//public const String[] ToneStrings = new String[]{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
public const int ToneMin = -36;
public const int ToneMax = 89;
public const int NumNoteLines = 11;
public static int MouseMoveDiffMin = 2;
public const float MouseMoveOffTime = 3f;
public const int MaxNumPlayer = 3;
public const int MaxScore = 10000;
public const int LinebonusScore = 1000;
public const int MinScoreForDB = 100;
public const float LyricHelperEnableTime = 5f;
public const float LyricHelperMoveTime = 1.5f;
public const float LyricHelperMinTime = 0.2f;
public const bool TabNavigation = false;
public static string GetVersionText()
{
string sVersion = "v" + iVersionMajor.ToString() + "." +
iVersionMinor.ToString() + "." +
iVersionSub.ToString();
if (VersionRevision != ERevision.Release)
sVersion += " " + GetVersionStatus() + String.Format(" ({0:0000)}", iBuild);
return sVersion;
}
public static string GetFullVersionText()
{
string sVersion = sProgramName;
if (sProgramCodeName != String.Empty)
sVersion += " \"" + sProgramCodeName + "\"";
return sVersion += " " + GetVersionText();
}
public static string GetVersionStatus()
{
string _Result = String.Empty;
if (VersionRevision != ERevision.Release)
_Result = Enum.GetName(typeof(ERevision), VersionRevision);
return _Result;
}
public static float GetRenderAspect()
{
return (float)iRenderW / (float)iRenderH;
}
public static void MouseInacive()
{
MouseMoveDiffMin = 15;
}
public static void MouseActive()
{
MouseMoveDiffMin = 3;
}
}
}
+871
View File
@@ -0,0 +1,871 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Song;
using Vocaluxe.Menu;
namespace Vocaluxe.Base
{
public struct SongPointer
{
public int SongID;
public string SortString;
public int CatIndex;
public bool Visible;
public SongPointer(int ID, string sortString)
{
SongID = ID;
SortString = sortString;
CatIndex = -1;
Visible = false;
}
}
public class CCategory
{
public string Name = String.Empty;
public STexture CoverTextureSmall = new STexture();
public STexture CoverTextureBig = new STexture();
public CCategory(string name, STexture CoverSmall, STexture CoverBig)
{
Name = name;
CoverTextureSmall = CoverSmall;
CoverTextureBig = CoverBig;
}
}
static class CSongs
{
private static List<CSong> _Songs = new List<CSong>();
private static SongPointer[] _SongsSortList = new SongPointer[0];
private static List<CSong> _SongsForRandom = new List<CSong>();
private static CHelper Helper = new CHelper();
private static bool _SongsLoaded = false;
private static bool _CoverLoaded = false;
private static int _CoverLoadIndex = -1;
private static int _CatIndex = -1;
private static List<CCategory> _Categories = new List<CCategory>();
private static Stopwatch _CoverLoadTimer = new Stopwatch();
private static string _SearchFilter = String.Empty;
private static EOffOn _Tabs = CConfig.Tabs;
public static string SearchFilter
{
get { return _SearchFilter; }
set
{
_SearchFilter = value;
if (_SearchFilter.Length > 0)
{
_Sort(CConfig.SongSorting, EOffOn.TR_CONFIG_OFF, _SearchFilter);
}
else
{
Sort();
}
}
}
public static EOffOn Tabs
{
get { return _Tabs; }
}
public static bool SongsLoaded
{
get { return _SongsLoaded; }
}
public static bool CoverLoaded
{
get
{
if (_SongsLoaded && NumAllSongs == 0)
_CoverLoaded = true;
return _CoverLoaded;
}
}
public static int NumAllSongs
{
get { return _Songs.Count; }
}
public static int NumVisibleSongs
{
get
{
int Result = 0;
foreach (SongPointer sp in _SongsSortList)
{
if (sp.Visible)
Result++;
}
return Result;
}
}
public static int NumCategories
{
get { return _Categories.Count; }
}
public static int Category
{
get { return _CatIndex; }
set
{
if ((_Categories.Count > value) && (value >= -1))
{
_CatIndex = value;
for (int i = 0; i < _SongsSortList.Length; i++)
{
_SongsSortList[i].Visible = (_SongsSortList[i].CatIndex == _CatIndex);
}
}
}
}
/// <summary>
/// Returns the number of song in the category specified with CatIndex
/// </summary>
/// <param name="CatIndex">Category index</param>
/// <returns></returns>
public static int NumSongsInCategory(int CatIndex)
{
if (_Categories.Count <= CatIndex || CatIndex < 0)
return 0;
int num = 0;
for (int i = 0; i < _SongsSortList.Length; i++)
{
if (_SongsSortList[i].CatIndex == CatIndex)
num++;
}
return num;
}
public static void NextCategory()
{
if (Category == _Categories.Count - 1)
Category = 0;
else
Category++;
}
public static void PrevCategory()
{
if (Category == 0)
Category = _Categories.Count - 1;
else
Category--;
}
public static int GetNextSongWithoutCover(ref CSong Song)
{
if (!SongsLoaded)
return -1;
if (_Songs.Count > _CoverLoadIndex + 1)
{
_CoverLoadIndex++;
Song = _Songs[_CoverLoadIndex];
return _CoverLoadIndex;
}
return -2;
}
public static int NumSongsWithCoverLoaded
{
get { return _CoverLoadIndex + 1; }
}
public static void SetCoverSmall(int SongIndex, STexture Texture)
{
if (!_SongsLoaded)
return;
if (SongIndex <= _Songs.Count)
{
_Songs[SongIndex].CoverTextureSmall = Texture;
//_Songs[SongIndex].CoverSmallLoaded = true;
}
if (SongIndex == _Songs.Count - 1)
_CoverLoaded = true;
}
public static void SetCoverBig(int SongIndex, STexture Texture)
{
if (!_SongsLoaded)
return;
if (SongIndex <= _Songs.Count)
{
_Songs[SongIndex].CoverTextureBig = Texture;
_Songs[SongIndex].CoverBigLoaded = true;
}
if (SongIndex == _Songs.Count - 1)
_CoverLoaded = true;
}
public static string GetActualCategoryName()
{
if ((_Categories.Count > 0) && (_CatIndex >= 0) && (_Categories.Count > _CatIndex))
return _Categories[_CatIndex].Name;
else
return String.Empty;
}
public static CSong GetSong(int SongID)
{
foreach (CSong song in _Songs)
{
if (song.ID == SongID)
return song;
}
return null;
}
public static int GetVisibleSongNumber(int SongID)
{
int i = -1;
foreach (CSong song in VisibleSongs)
{
i++;
if (song.ID == SongID)
return i;
}
return i;
}
public static int GetRandomSong()
{
if (_SongsForRandom.Count == 0)
{
UpdateRandomSongList();
}
if (_SongsForRandom.Count == 0)
return -1;
CSong song = _SongsForRandom[CGame.Rand.Next(0, _SongsForRandom.Count-1)];
_SongsForRandom.Remove(song);
return GetVisibleSongNumber(song.ID);
}
public static void UpdateRandomSongList()
{
_SongsForRandom.Clear();
_SongsForRandom.AddRange(VisibleSongs);
}
public static CSong[] AllSongs
{
get { return _Songs.ToArray(); }
}
public static CSong[] VisibleSongs
{
get
{
List<CSong> songs = new List<CSong>();
foreach (SongPointer sp in _SongsSortList)
{
if (sp.Visible)
songs.Add(_Songs[sp.SongID]);
}
return songs.ToArray();
}
}
public static CCategory[] Categories
{
get { return _Categories.ToArray(); }
}
public static void Sort()
{
_Sort(CConfig.SongSorting, CConfig.Tabs, String.Empty);
}
public static void Sort(ESongSorting sorting)
{
_Sort(sorting, CConfig.Tabs, String.Empty);
}
private static void _Sort(ESongSorting sorting, EOffOn Tabs, string SearchString)
{
if (_Songs.Count == 0)
return;
_Categories.Clear();
string category = String.Empty;
_Tabs = Tabs;
List<SongPointer> _SortList = new List<SongPointer>();
List<CSong> _SongList = new List<CSong>();
foreach (CSong song in _Songs)
{
if (SearchString == String.Empty)
_SongList.Add(song);
else
{
if (song.Title.ToUpper().Contains(SearchString.ToUpper()) || song.Artist.ToUpper().Contains(SearchString.ToUpper()))
_SongList.Add(song);
}
}
switch (sorting)
{
case ESongSorting.TR_CONFIG_EDITION:
foreach (CSong song in _SongList)
{
if (song.Edition.Count == 0)
_SortList.Add(new SongPointer(song.ID, String.Empty));
else
{
for (int i = 0; i < song.Edition.Count; i++)
{
_SortList.Add(new SongPointer(song.ID, song.Edition[i]));
}
}
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.ToUpper().CompareTo(s2.SortString.ToUpper());
if (res == 0)
{
res = _Songs[s1.SongID].Artist.ToUpper().CompareTo(_Songs[s2.SongID].Artist.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i = 0; i < _SongsSortList.Length; i++ )
{
if (_SongsSortList[i].SortString.Length > 0)
{
if (_SongsSortList[i].SortString != category)
{
category = _SongsSortList[i].SortString;
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
else
{
if (CLanguage.Translate("TR_SCREENSONG_NOEDITION") != category)
{
category = CLanguage.Translate("TR_SCREENSONG_NOEDITION");
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
}
break;
case ESongSorting.TR_CONFIG_GENRE:
foreach (CSong song in _SongList)
{
if (song.Genre.Count == 0)
_SortList.Add(new SongPointer(song.ID, String.Empty));
else
{
for (int i = 0; i < song.Genre.Count; i++)
{
_SortList.Add(new SongPointer(song.ID, song.Genre[i]));
}
}
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.ToUpper().CompareTo(s2.SortString.ToUpper());
if (res == 0)
{
res = _Songs[s1.SongID].Artist.ToUpper().CompareTo(_Songs[s2.SongID].Artist.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i = 0; i < _SongsSortList.Length; i++)
{
if (_SongsSortList[i].SortString.Length > 0)
{
if (_SongsSortList[i].SortString != category)
{
category = _SongsSortList[i].SortString;
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
else
{
if (CLanguage.Translate("TR_SCREENSONG_NOGENRE") != category)
{
category = CLanguage.Translate("TR_SCREENSONG_NOGENRE");
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
}
break;
case ESongSorting.TR_CONFIG_NONE:
foreach (CSong song in _SongList)
{
_SortList.Add(new SongPointer(song.ID, String.Empty));
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.ToUpper().CompareTo(s2.SortString.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i = 0; i < _SongsSortList.Length; i++)
{
_SongsSortList[i].CatIndex = 0;
}
category = CLanguage.Translate("TR_SCREENSONG_ALLSONGS");
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
break;
case ESongSorting.TR_CONFIG_FOLDER:
foreach (CSong song in _SongList)
{
_SortList.Add(new SongPointer(song.ID, song.FolderName));
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.ToUpper().CompareTo(s2.SortString.ToUpper());
if (res == 0)
{
res = _Songs[s1.SongID].Artist.ToUpper().CompareTo(_Songs[s2.SongID].Artist.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i = 0; i < _SongsSortList.Length; i++)
{
if (_SongsSortList[i].SortString != category)
{
category = _SongsSortList[i].SortString;
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
break;
case ESongSorting.TR_CONFIG_ARTIST:
foreach (CSong song in _SongList)
{
_SortList.Add(new SongPointer(song.ID, song.Artist));
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.ToUpper().CompareTo(s2.SortString.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i = 0; i < _SongsSortList.Length; i++)
{
if (_SongsSortList[i].SortString != category)
{
category = _SongsSortList[i].SortString;
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
break;
case ESongSorting.TR_CONFIG_ARTIST_LETTER:
foreach (CSong song in _SongList)
{
_SortList.Add(new SongPointer(song.ID, song.Artist));
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.ToUpper().CompareTo(s2.SortString.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
int NotLetterCat = -1;
for (int i=0; i < _SongsSortList.Length; i++)
{
Char firstLetter = Char.ToUpper(_SongsSortList[i].SortString[0]);
if (!Char.IsLetter(firstLetter))
{
firstLetter = '#';
}
if (firstLetter.ToString() != category)
{
if (firstLetter != '#' || NotLetterCat == -1)
{
category = firstLetter.ToString();
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
_SongsSortList[i].CatIndex = _Categories.Count - 1;
if (firstLetter == '#')
NotLetterCat = _SongsSortList[i].CatIndex;
}
else
_SongsSortList[i].CatIndex = NotLetterCat;
}
else
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
break;
case ESongSorting.TR_CONFIG_TITLE_LETTER:
foreach (CSong song in _SongList)
{
_SortList.Add(new SongPointer(song.ID, song.Title));
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.ToUpper().CompareTo(s2.SortString.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Artist.ToUpper().CompareTo(_Songs[s2.SongID].Artist.ToUpper());
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
NotLetterCat = -1;
for (int i=0; i < _SongsSortList.Length; i++)
{
Char firstLetter = Char.ToUpper(_SongsSortList[i].SortString[0]);
if (!Char.IsLetter(firstLetter))
{
firstLetter = '#';
}
if (firstLetter.ToString() != category)
{
if (firstLetter != '#' || NotLetterCat == -1)
{
category = firstLetter.ToString();
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
_SongsSortList[i].CatIndex = _Categories.Count - 1;
if (firstLetter == '#')
NotLetterCat = _SongsSortList[i].CatIndex;
}
else
_SongsSortList[i].CatIndex = NotLetterCat;
}
else
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
break;
case ESongSorting.TR_CONFIG_DECADE:
foreach (CSong song in _SongList)
{
_SortList.Add(new SongPointer(song.ID, song.Year));
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.CompareTo(s2.SortString);
if (res == 0)
{
res = _Songs[s1.SongID].Artist.ToUpper().CompareTo(_Songs[s2.SongID].Artist.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i=0; i < _SongsSortList.Length; i++)
{
if (_SongsSortList[i].SortString.Length > 0 && !_SongsSortList[i].SortString.Equals("0000"))
{
String decade = _SongsSortList[i].SortString.Substring(0, 3) + "0 - " + _SongsSortList[i].SortString.Substring(0, 3) + "9";
if (decade != category)
{
category = decade;
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
else
{
if (CLanguage.Translate("TR_SCREENSONG_NOYEAR") != category)
{
category = CLanguage.Translate("TR_SCREENSONG_NOYEAR");
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
}
break;
case ESongSorting.TR_CONFIG_YEAR:
foreach (CSong song in _SongList)
{
_SortList.Add(new SongPointer(song.ID, song.Year));
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.CompareTo(s2.SortString);
if (res == 0)
{
res = _Songs[s1.SongID].Artist.ToUpper().CompareTo(_Songs[s2.SongID].Artist.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i=0; i < _SongsSortList.Length; i++)
{
if (_SongsSortList[i].SortString.Length > 0 && !_SongsSortList[i].SortString.Equals("0000"))
{
if (_SongsSortList[i].SortString != category)
{
category = _SongsSortList[i].SortString;
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
else
{
if (CLanguage.Translate("TR_SCREENSONG_NOYEAR") != category)
{
category = CLanguage.Translate("TR_SCREENSONG_NOYEAR");
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
}
break;
case ESongSorting.TR_CONFIG_LANGUAGE:
foreach (CSong song in _SongList)
{
if (song.Language.Count == 0)
_SortList.Add(new SongPointer(song.ID, String.Empty));
else
{
for (int i = 0; i < song.Language.Count; i++)
{
_SortList.Add(new SongPointer(song.ID, song.Language[i]));
}
}
}
_SortList.Sort(delegate(SongPointer s1, SongPointer s2)
{
int res = s1.SortString.CompareTo(s2.SortString);
if (res == 0)
{
res = _Songs[s1.SongID].Artist.ToUpper().CompareTo(_Songs[s2.SongID].Artist.ToUpper());
if (res == 0)
{
return _Songs[s1.SongID].Title.ToUpper().CompareTo(_Songs[s2.SongID].Title.ToUpper());
}
return res;
}
return res;
});
_SongsSortList = _SortList.ToArray();
_Categories.Clear();
for (int i=0; i < _SongsSortList.Length; i++)
{
if (_SongsSortList[i].SortString.Length > 0)
{
if (_SongsSortList[i].SortString != category)
{
category = _SongsSortList[i].SortString;
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
else
{
if (CLanguage.Translate("TR_SCREENSONG_NOLANGUAGE") != category)
{
category = CLanguage.Translate("TR_SCREENSONG_NOLANGUAGE");
_Categories.Add(new CCategory(category, new STexture(-1), new STexture(-1)));
}
_SongsSortList[i].CatIndex = _Categories.Count - 1;
}
}
break;
default:
break;
}
if (_Tabs == EOffOn.TR_CONFIG_OFF)
{
_Categories.Clear();
_Categories.Add(new CCategory("", new STexture(-1), new STexture(-1)));
for (int i = 0; i < _SongsSortList.Length; i++)
{
_SongsSortList[i].CatIndex = 0;
}
}
foreach (CCategory cat in _Categories)
{
STexture cover = CCover.Cover(cat.Name);
cat.CoverTextureSmall = cover;
}
}
public static void LoadSongs()
{
CLog.StartBenchmark(1, "Load Songs");
_SongsLoaded = false;
_Songs.Clear();
CLog.StartBenchmark(2, "List Songs");
List<string> files = new List<string>();
foreach (string p in CConfig.SongFolder)
{
string path = p;
files.AddRange(Helper.ListFiles(path, "*.txt", true, true));
files.AddRange(Helper.ListFiles(path, "*.txd", true, true));
}
CLog.StopBenchmark(2, "List Songs");
CLog.StartBenchmark(2, "Read TXTs");
foreach (string file in files)
{
CSong Song = new CSong();
if (Song.ReadTXTSong(file))
{
Song.ID = _Songs.Count;
_Songs.Add(Song);
}
}
CLog.StopBenchmark(2, "Read TXTs");
CLog.StartBenchmark(2, "Sort Songs");
Sort(CConfig.SongSorting);
CLog.StopBenchmark(2, "Sort Songs");
Category = -1;
_SongsLoaded = true;
CLog.StopBenchmark(1, "Load Songs ");
}
public static void LoadCover(long WaitTime)
{
if (!SongsLoaded)
return;
if (CoverLoaded)
return;
if (!_CoverLoadTimer.IsRunning)
{
_CoverLoadTimer.Reset();
_CoverLoadTimer.Start();
}
STexture texture = new STexture(-1);
if (_CoverLoadTimer.ElapsedMilliseconds >= WaitTime)
{
CSong song = new CSong();
int i = GetNextSongWithoutCover(ref song);
if (i < 0)
return;
song.ReadNotes();
if (song.CoverFileName != String.Empty)
{
if (!CDataBase.GetCover(Path.Combine(song.Folder, song.CoverFileName), ref texture, CConfig.CoverSize))
texture = CCover.NoCover;
}
else
texture = CCover.NoCover;
SetCoverSmall(i, texture);
SetCoverBig(i, texture);
_CoverLoadTimer.Reset();
_CoverLoadTimer.Start();
}
}
}
}
+653
View File
@@ -0,0 +1,653 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Vocaluxe.Lib.Sound;
namespace Vocaluxe.Base
{
enum ESounds
{
T440
}
static class CSound
{
#region Playback
private static IPlayback _Playback = null;
public static bool PlaybackInit()
{
switch (CConfig.PlayBackLib)
{
case EPlaybackLib.BASS:
_Playback = new CBassPlay();
break;
case EPlaybackLib.PortAudio:
_Playback = new CPortAudioPlay();
break;
case EPlaybackLib.NAudio:
_Playback = new CNAudioPlay();
break;
case EPlaybackLib.OpenAL:
_Playback = new COpenALPlay();
break;
default:
_Playback = new CBassPlay();
break;
}
return true;
}
public static void SetGlobalVolume(float Volume)
{
_Playback.SetGlobalVolume(Volume);
}
public static int GetStreamCount()
{
return _Playback.GetStreamCount();
}
public static void CloseAllStreams()
{
_Playback.CloseAll();
}
#region Stream Handling
public static int Load(string Media)
{
return _Playback.Load(Media);
}
public static int Load(string Media, bool Prescan)
{
return _Playback.Load(Media, Prescan);
}
public static void Close(int Stream)
{
_Playback.Close(Stream);
}
public static void Play(int Stream)
{
_Playback.Play(Stream);
}
public static void Play(int Stream, bool Loop)
{
_Playback.Play(Stream, Loop);
}
public static void Pause(int Stream)
{
_Playback.Pause(Stream);
}
public static void Stop(int Stream)
{
_Playback.Stop(Stream);
}
public static void Fade(int Stream, float TargetVolume, float Seconds)
{
_Playback.Fade(Stream, TargetVolume, Seconds);
}
public static void FadeAndStop(int Stream, float TargetVolume, float Seconds)
{
_Playback.FadeAndStop(Stream, TargetVolume, Seconds);
}
public static void SetStreamVolume(int Stream, float Volume)
{
_Playback.SetStreamVolume(Stream, Volume);
}
public static float GetLength(int Stream)
{
return _Playback.GetLength(Stream);
}
public static float GetPosition(int Stream)
{
return _Playback.GetPosition(Stream);
}
public static bool IsPlaying(int Stream)
{
return _Playback.IsPlaying(Stream);
}
public static bool IsPaused(int Stream)
{
return _Playback.IsPaused(Stream);
}
public static bool IsFinished(int Stream)
{
return _Playback.IsFinished(Stream);
}
public static void Update()
{
_Playback.Update();
}
public static void SetPosition(int Stream, float Position)
{
_Playback.SetPosition(Stream, Position);
}
#endregion Stream Handling
#endregion Playback
#region Sounds
public static int PlaySound(ESounds Sound)
{
string file = Path.Combine(Environment.CurrentDirectory, CSettings.sFolderSounds);
switch (Sound)
{
case ESounds.T440:
file = Path.Combine(file, CSettings.sSoundT440);
break;
default:
break;
}
if (file == String.Empty)
return -1;
int stream = CSound.Load(file);
float length = CSound.GetLength(stream);
CSound.Play(stream);
CSound.FadeAndStop(stream, 100f, length);
return stream;
}
#endregion Sounds
#region Record
private static IRecord _Record = null;
public static bool RecordInit()
{
switch (CConfig.RecordLib)
{
case ERecordLib.BASS:
_Record = new CBassRecord();
break;
case ERecordLib.PortAudio:
_Record = new CPortAudioRecord();
break;
default:
_Record = new CBassRecord();
break;
}
return true;
}
public static void RecordCloseAll()
{
_Record.CloseAll();
}
public static bool RecordStart()
{
SRecordDevice[] devices = RecordGetDevices();
return _Record.Start(devices);
}
public static bool RecordStop()
{
return _Record.Stop();
}
public static void AnalyzeBuffer(int Player)
{
_Record.AnalyzeBuffer(Player);
}
public static int RecordGetToneAbs(int Player)
{
return _Record.GetToneAbs(Player);
}
public static int RecordGetTone(int Player)
{
return _Record.GetTone(Player);
}
public static void RecordSetTone(int Player, int Tone)
{
_Record.SetTone(Player, Tone);
}
public static bool RecordToneValid(int Player)
{
return _Record.ToneValid(Player);
}
public static float RecordGetMaxVolume(int Player)
{
return _Record.GetMaxVolume(Player);
}
public static SRecordDevice[] RecordGetDevices()
{
SRecordDevice[] devices = _Record.RecordDevices();
if (devices != null)
{
for (int dev = 0; dev < devices.Length; dev++)
{
for (int inp = 0; inp < devices[dev].Inputs.Count; inp++)
{
SInput input = devices[dev].Inputs[inp];
input.PlayerChannel1 = GetPlayerFromMicConfig(devices[dev].Name, devices[dev].Driver, input.Name, 1);
input.PlayerChannel2 = GetPlayerFromMicConfig(devices[dev].Name, devices[dev].Driver, input.Name, 2);
devices[dev].Inputs[inp] = input;
}
}
return devices;
}
return null;
}
private static int GetPlayerFromMicConfig(string device, string devicedriver, string input, int channel)
{
for (int p = 0; p < CSettings.MaxNumPlayer; p++)
{
if (CConfig.MicConfig[p].Channel != 0 &&
CConfig.MicConfig[p].DeviceName == device &&
CConfig.MicConfig[p].DeviceDriver == devicedriver &&
CConfig.MicConfig[p].InputName == input &&
CConfig.MicConfig[p].Channel == channel)
{
return p + 1;
}
}
return 0;
}
#endregion Record
}
class CBuffer
{
private const double BaseToneFreq = 65.4064;
private const int NumHalfTones = 47;
private Int16[] _AnalysisBuffer = new Int16[4096];
private Object _AnalysisBufferLock = new Object();
private bool _ToneValid = false;
private int _Tone = 0;
private int _ToneAbs = 0;
private double _MaxVolume = 0.0;
private bool _NewSamples = false;
private MemoryStream _Stream; // full buffer
public int ToneAbs
{
get { return _ToneAbs; }
}
public int Tone
{
get { return _Tone; }
set { _Tone = value; }
}
public float MaxVolume
{
get
{
return (float)_MaxVolume;
}
}
public bool ToneValid
{
get { return _ToneValid; }
}
public CBuffer()
{
_Stream = new MemoryStream();
}
public long Length
{
get { return _Stream.Length; }
}
public byte[] Buffer
{
get { return _Stream.ToArray(); }
}
public void Reset()
{
_Stream.SetLength(0L);
_AnalysisBuffer = new Int16[_AnalysisBuffer.Length];
_ToneValid = false;
_ToneAbs = 0;
_Tone = 0;
_NewSamples = false;
}
public void Add(byte[] bytes)
{
_Stream.Write(bytes, 0, bytes.Length);
}
public void ProcessNewBuffer(byte[] buffer)
{
// apply software boost
//BoostBuffer(Buffer, BufferSize);
// voice passthrough (send data to playback-device)
//if (assigned(fVoiceStream)) then
//fVoiceStream.WriteData(Buffer, BufferSize);
int BufferOffset = 0;
int SampleCount = (int)Math.Floor(buffer.Length / 2.0);
if (SampleCount > _AnalysisBuffer.Length)
{
BufferOffset = (SampleCount - _AnalysisBuffer.Length) * 2;
SampleCount = _AnalysisBuffer.Length;
}
lock (_AnalysisBufferLock)
{
try
{
// move old samples to the beginning of the array (if necessary)
for (int i = 0; i < _AnalysisBuffer.Length - SampleCount; i++)
{
_AnalysisBuffer[i] = _AnalysisBuffer[i + SampleCount];
}
byte[] b = new byte[2];
// copy new samples to analysis buffer
for (int i = 0; i < SampleCount; i++)
{
b[0] = buffer[BufferOffset + i * 2];
b[1] = buffer[BufferOffset + i * 2 + 1];
_AnalysisBuffer[_AnalysisBuffer.Length - SampleCount + i] = BitConverter.ToInt16(b, 0);
}
}
catch (Exception)
{
}
Add(buffer);
_NewSamples = true;
}
}
public void AnalyzeBuffer()
{
lock (_AnalysisBufferLock)
{
if (!_NewSamples)
return;
try
{
// find maximum volume
_MaxVolume = 0;
for (int i = 0; i < _AnalysisBuffer.Length/4; i++)
{
float Volume = Math.Abs((float)_AnalysisBuffer[i]) / (float)Int16.MaxValue;
if (Volume > MaxVolume)
_MaxVolume = Volume;
}
if (_MaxVolume >= 0.2f)
{
// analyse the current voice pitch
AnalyzeByAutocorrelation();
_ToneValid = true;
}
else
_ToneValid = false;
_NewSamples = false;
}
catch (Exception)
{
}
}
}
private void AnalyzeByAutocorrelation()
{
const double HalftoneBase = 1.05946309436; // 2^(1/12) -> HalftoneBase^12 = 2 (one octave)
// prepare to analyze
double MaxWeight = -1.0;
int MaxTone = 0;
// analyze halftones
// Note: at the lowest tone (~65Hz) and a buffer-size of 4096
// at 44.1 (or 48kHz) only 6 (or 5) samples are compared, this might be
// too few samples -> use a bigger buffer-size
for (int ToneIndex = 0; ToneIndex < NumHalfTones; ToneIndex++)
{
double CurFreq = BaseToneFreq * Math.Pow(HalftoneBase, ToneIndex);
double CurWeight = AnalyzeAutocorrelationFreq(CurFreq);
// TODO: prefer higher frequencies (use >= or use downto)
if (CurWeight > MaxWeight /* && (Math.Abs(ToneIndex - _ToneAbs) < 5 || _ToneAbs == 0)*/)
{
// this frequency has a higher weight
MaxWeight = CurWeight;
MaxTone = ToneIndex;
}
}
_ToneAbs = MaxTone;
_Tone = MaxTone % 12;
}
private double AnalyzeAutocorrelationFreq(double Freq)
{
int SampleIndex = 0; // index of sample to analyze
int SamplesPerPeriod = (int)Math.Round(44100.0 / Freq); // samples in one period
int CorrelatingSampleIndex = SampleIndex + SamplesPerPeriod; // index of sample one period ahead
double AccumDist = 0.0; // accumulated distances
// compare correlating samples
while (CorrelatingSampleIndex < _AnalysisBuffer.Length)
{
// calc distance (correlation: 1-dist) to corresponding sample in next period
// distance (0=equal .. 1=totally different) between correlated samples
double Dist = Math.Abs((double)_AnalysisBuffer[SampleIndex] - _AnalysisBuffer[CorrelatingSampleIndex]) / (double)Int16.MaxValue;
AccumDist += Dist;
SampleIndex++;
CorrelatingSampleIndex++;
}
return 1 - AccumDist / _AnalysisBuffer.Length;
}
}
class CSyncTimer
{
private PT1 _ExternTime;
private Stopwatch _Timer;
private float _SetValue;
public float Time
{
get
{
long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
long ticks = _Timer.ElapsedTicks;
float dt = _Timer.ElapsedMilliseconds / 1000f;
if (nanosecPerTick > 0L)
dt = (float)(ticks * nanosecPerTick / 1000000000.0);
return _SetValue + dt;
}
set
{
_ExternTime.Time = value;
_SetValue = value;
_Timer.Reset();
_Timer.Start();
}
}
public CSyncTimer(float CurrentTime, float K, float T)
{
_ExternTime = new PT1(CurrentTime, K, T);
_Timer = new Stopwatch();
_SetValue = CurrentTime;
}
public float Update(float NewTime)
{
float et = _ExternTime.Update(NewTime);
float dt = Time;
float diff = _ExternTime.Time - dt;
if (Math.Abs(diff) > 0.05f)
{
_Timer.Reset();
_Timer.Start();
_SetValue = dt + diff;
dt = _SetValue;
//Console.WriteLine("DRIFTED!!! " + diff.ToString());
}
else
{
if (diff > 0.01f)
_SetValue += 0.000025f;
if (diff < -0.01f)
_SetValue -= 0.000025f;
}
//Console.WriteLine(diff.ToString());
return dt;
}
public void Pause()
{
_ExternTime.Pause();
_Timer.Stop();
}
public void Resume()
{
_ExternTime.Resume();
_Timer.Start();
}
}
class PT1
{
private float _CurrentTime;
private float _OldTime;
private Stopwatch _STimer;
private float _K;
private float _T;
public float Time
{
get
{
long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
long ticks = _STimer.ElapsedTicks;
float dt = _STimer.ElapsedMilliseconds / 1000f;
if (nanosecPerTick > 0L)
dt = (float)(ticks * nanosecPerTick / 1000000000.0);
return _CurrentTime + dt;
}
set
{
if (value < 0f)
return;
_CurrentTime = value;
_OldTime = value;
_STimer.Reset();
_STimer.Start();
}
}
public PT1(float CurrentTime, float K, float T)
{
_CurrentTime = CurrentTime;
_OldTime = CurrentTime;
_STimer = new Stopwatch();
_K = K;
_T = T;
}
public float Update(float NewTime)
{
_STimer.Stop();
long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
long ticks = _STimer.ElapsedTicks;
float dt = _STimer.ElapsedMilliseconds / 1000f;
if (nanosecPerTick > 0L)
dt = (float)(ticks * nanosecPerTick / 1000000000.0);
float Ts = 0f;
if (dt > 0)
Ts = 1 / (_T / dt + 1);
_CurrentTime = Ts * (_K * NewTime - _OldTime) + _OldTime;
_OldTime = _CurrentTime;
_STimer.Reset();
_STimer.Start();
return _CurrentTime;
}
public void Pause()
{
_STimer.Stop();
}
public void Resume()
{
_STimer.Start();
}
}
}
+929
View File
@@ -0,0 +1,929 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Menu;
using Vocaluxe.Menu.SingNotes;
using Vocaluxe.Menu.SongMenu;
using Vocaluxe.Screens;
namespace Vocaluxe.Base
{
#region Structs
struct Theme
{
public string Name;
public string Author;
public string SkinFolder;
public int ThemeVersionMajor;
public int ThemeVersionMinor;
public string Path;
public string FileName;
}
struct SkinElement
{
public string Name;
public string Value;
public STexture Texture;
public int VideoIndex;
}
struct Skin
{
public string Name;
public string Author;
public int SkinVersionMajor;
public int SkinVersionMinor;
public string Path;
public string FileName;
public List<SkinElement> SkinList;
public List<SkinElement> VideoList;
public SColors ThemeColors;
}
struct SColors
{
public SColorF[] Player;
public SColorScheme[] ColorSchemes;
}
struct SColorScheme
{
public string Name;
public SColorF Color;
}
struct SCursor
{
public string SkinName;
public float w;
public float h;
public float r;
public float g;
public float b;
public float a;
public string color;
}
#endregion Structs
static class CTheme
{
// Version number for main theme and skin files. Increment it, if you've changed something on the theme files!
const int ThemeSystemVersion = 4;
const int SkinSystemVersion = 3;
#region Vars
private static XmlWriterSettings _settings = new XmlWriterSettings();
private static List<Theme> _Themes = new List<Theme>();
public static string[] ThemeNames
{
get
{
List<string> names = new List<string>();
foreach (Theme th in _Themes)
{
names.Add(th.Name);
}
return names.ToArray();
}
}
private static List<Skin> _Skins = new List<Skin>();
public static string[] SkinNames
{
get
{
List<string> names = new List<string>();
foreach (Skin sk in _Skins)
{
names.Add(sk.Name);
}
return names.ToArray();
}
}
public static SCursor Cursor = new SCursor();
#endregion Vars
#region Theme and Skin loading and writing
public static void InitTheme()
{
_settings.Indent = true;
_settings.Encoding = Encoding.UTF8;
_settings.ConformanceLevel = ConformanceLevel.Document;
//ThemeColors.Player = new SColorF[6];
ListThemes();
ListSkins();
LoadSkins();
LoadTheme();
}
public static void LoadSkins()
{
for (int index = 0; index < _Skins.Count; index++)
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(Path.Combine(_Skins[index].Path, _Skins[index].FileName));
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception e)
{
CLog.LogError("Error loading skin " + _Skins[index].FileName + ": " + e.Message);
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
if (loaded)
{
string value = String.Empty;
// load skins/textures
for (int i = 0; i < _Skins[index].SkinList.Count; i++)
{
CHelper.GetValueFromXML("//root/Skins/" + _Skins[index].SkinList[i].Name, navigator, ref value, String.Empty);
SkinElement sk = new SkinElement();
sk.Name = _Skins[index].SkinList[i].Name;
sk.Value = value;
sk.VideoIndex = -1;
sk.Texture = CDraw.AddTexture(Path.Combine(_Skins[index].Path, sk.Value));
_Skins[index].SkinList[i] = sk;
}
// load videos
for (int i = 0; i < _Skins[index].VideoList.Count; i++)
{
CHelper.GetValueFromXML("//root/Videos/" + _Skins[index].VideoList[i].Name, navigator, ref value, String.Empty);
SkinElement sk = new SkinElement();
sk.Name = _Skins[index].VideoList[i].Name;
sk.Value = value;
sk.VideoIndex = CVideo.VdLoad(Path.Combine(_Skins[index].Path, sk.Value));
CVideo.VdSetLoop(sk.VideoIndex, true);
CVideo.VdPause(sk.VideoIndex);
sk.Texture = new STexture(-1);
_Skins[index].VideoList[i] = sk;
}
// load colors
LoadColors(navigator, index);
}
}
}
public static void UnloadSkins()
{
for (int i = 0; i < _Skins.Count; i++)
{
for (int j = 0; j < _Skins[i].SkinList.Count; j++)
{
STexture Texture = _Skins[i].SkinList[j].Texture;
CDraw.RemoveTexture(ref Texture);
}
for (int j = 0; j < _Skins[i].VideoList.Count; j++)
{
CVideo.VdClose(_Skins[i].VideoList[j].VideoIndex);
STexture VideoTexture = _Skins[i].VideoList[j].Texture;
CDraw.RemoveTexture(ref VideoTexture);
}
}
_Skins.Clear();
}
public static void LoadTheme()
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
int index = 0;
for (int i = 0; i < _Themes.Count; i++)
{
if (_Themes[i].Name == CConfig.Theme)
index = i;
}
try
{
xPathDoc = new XPathDocument(Path.Combine(_Themes[index].Path, _Themes[index].FileName));
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception e)
{
CLog.LogError("Error loading theme " + _Themes[index].FileName + ": " + e.Message);
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
if (loaded)
{
int skinIndex = GetSkinIndex();
// Load Cursor
LoadCursor(navigator, skinIndex);
// load fonts
CFonts.LoadThemeFonts(
_Themes[index].Name,
Path.Combine(Path.Combine(_Themes[index].Path, _Themes[index].SkinFolder), CSettings.sFolderThemeFonts),
navigator);
}
}
public static void SaveTheme()
{
SaveSkin();
int ThemeIndex = 0;
for (int i = 0; i < _Themes.Count; i++)
{
if (_Themes[i].Name == CConfig.Theme)
ThemeIndex = i;
}
#region ThemeMainFile
XmlWriter writer = XmlWriter.Create(Path.Combine(_Themes[ThemeIndex].Path, _Themes[ThemeIndex].FileName), _settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
// ThemeSystemVersion
writer.WriteElementString("ThemeSystemVersion", ThemeSystemVersion.ToString());
#region Info
writer.WriteStartElement("Info");
writer.WriteElementString("Name", _Themes[ThemeIndex].Name);
writer.WriteElementString("Author", _Themes[ThemeIndex].Author);
writer.WriteElementString("SkinFolder", _Themes[ThemeIndex].SkinFolder);
writer.WriteElementString("ThemeVersionMajor", _Themes[ThemeIndex].ThemeVersionMajor.ToString());
writer.WriteElementString("ThemeVersionMinor", _Themes[ThemeIndex].ThemeVersionMinor.ToString());
writer.WriteEndElement();
#endregion Info
// Cursor
SaveCursor(writer);
// save fonts
CFonts.SaveThemeFonts(_Themes[ThemeIndex].Name, writer);
// End of File
writer.WriteEndElement(); //end of root
writer.WriteEndDocument();
writer.Flush();
writer.Close();
#endregion ThemeMainFile
}
public static void SaveSkin()
{
for (int SkinIndex = 0; SkinIndex < _Skins.Count; SkinIndex++)
{
XmlWriter writer = XmlWriter.Create(Path.Combine(_Skins[SkinIndex].Path, _Skins[SkinIndex].FileName), _settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
// ThemeSystemVersion
writer.WriteElementString("SkinSystemVersion", SkinSystemVersion.ToString());
#region Info
writer.WriteStartElement("Info");
writer.WriteElementString("Name", _Skins[SkinIndex].Name);
writer.WriteElementString("Author", _Skins[SkinIndex].Author);
writer.WriteElementString("SkinVersionMajor", _Skins[SkinIndex].SkinVersionMajor.ToString());
writer.WriteElementString("SkinVersionMinor", _Skins[SkinIndex].SkinVersionMinor.ToString());
writer.WriteEndElement();
#endregion Info
// save colors
SaveColors(writer, SkinIndex);
#region Skins
writer.WriteStartElement("Skins");
foreach (SkinElement element in _Skins[SkinIndex].SkinList)
{
writer.WriteElementString(element.Name, element.Value);
}
writer.WriteEndElement();
#endregion Skins
#region Videos
writer.WriteStartElement("Videos");
foreach (SkinElement element in _Skins[SkinIndex].VideoList)
{
writer.WriteElementString(element.Name, element.Value);
}
writer.WriteEndElement();
#endregion Videos
// End of File
writer.WriteEndElement(); //end of root
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}
private static void ListThemes()
{
CHelper Helper = new CHelper();
_Themes.Clear();
string path = Path.Combine(Directory.GetCurrentDirectory(), CSettings.sFolderThemes);
List<string> files = Helper.ListFiles(path, "*.xml", false);
foreach (string file in files)
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(Path.Combine(path, file));
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception e)
{
CLog.LogError("Error loading theme " + file + ": " + e.Message);
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
if (loaded)
{
Theme theme = new Theme();
int version = 0;
CHelper.TryGetIntValueFromXML("//root/ThemeSystemVersion", navigator, ref version);
if (version == ThemeSystemVersion)
{
CHelper.GetValueFromXML("//root/Info/Name", navigator, ref theme.Name, String.Empty);
if (theme.Name != String.Empty)
{
CHelper.GetValueFromXML("//root/Info/Author", navigator, ref theme.Author, String.Empty);
CHelper.GetValueFromXML("//root/Info/SkinFolder", navigator, ref theme.SkinFolder, String.Empty);
CHelper.TryGetIntValueFromXML("//root/Info/ThemeVersionMajor", navigator, ref theme.ThemeVersionMajor);
CHelper.TryGetIntValueFromXML("//root/Info/ThemeVersionMinor", navigator, ref theme.ThemeVersionMinor);
theme.Path = path;
theme.FileName = file;
_Themes.Add(theme);
}
}
else
{
string msg = "Can't load Theme \"" + file + "\", ";
if (version < ThemeSystemVersion)
msg += "the file ist outdated! ";
else
msg += "the file is for newer program versions! ";
msg += "Current ThemeSystemVersion is " + ThemeSystemVersion.ToString();
CLog.LogError(msg);
}
}
}
}
public static void ListSkins()
{
CHelper Helper = new CHelper();
int themeIndex = GetThemeIndex();
_Skins.Clear();
if (themeIndex < 0)
{
CLog.LogError("Error List Skins. Can't find Theme: " + CConfig.Theme);
return;
}
Theme theme = _Themes[themeIndex];
string path = Path.Combine(theme.Path, theme.SkinFolder);
List<string> files = Helper.ListFiles(path, "*.xml", false);
foreach (string file in files)
{
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(Path.Combine(path, file));
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception e)
{
CLog.LogError("Error loading skin " + file + ": " + e.Message);
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
if (loaded)
{
Skin skin = new Skin();
int version = 0;
CHelper.TryGetIntValueFromXML("//root/SkinSystemVersion", navigator, ref version);
if (version == SkinSystemVersion)
{
CHelper.GetValueFromXML("//root/Info/Name", navigator, ref skin.Name, String.Empty);
if (skin.Name != String.Empty)
{
CHelper.GetValueFromXML("//root/Info/Author", navigator, ref skin.Author, String.Empty);
skin.Path = path;
skin.FileName = file;
skin.SkinList = new List<SkinElement>();
List<string> names = CHelper.GetValuesFromXML("Skins", navigator);
foreach (string str in names)
{
SkinElement sk = new SkinElement();
sk.Name = str;
sk.Value = String.Empty;
skin.SkinList.Add(sk);
}
skin.VideoList = new List<SkinElement>();
names = CHelper.GetValuesFromXML("Videos", navigator);
foreach (string str in names)
{
SkinElement sk = new SkinElement();
sk.Name = str;
sk.Value = String.Empty;
skin.VideoList.Add(sk);
}
_Skins.Add(skin);
}
}
else
{
string msg = "Can't load Skin \"" + file + "\", ";
if (version < SkinSystemVersion)
msg += "the file ist outdated! ";
else
msg += "the file is for newer program versions! ";
msg += "Current SkinSystemVersion is " + SkinSystemVersion.ToString();
CLog.LogError(msg);
}
}
}
}
#endregion Theme and Skin loading and writing
#region Theme and Skin index handling
public static int GetSkinIndex()
{
for (int i = 0; i < _Skins.Count; i++)
{
if (_Skins[i].Name == CConfig.Skin)
{
return i;
}
}
return -1;
}
public static int GetThemeIndex()
{
for (int i = 0; i < _Themes.Count; i++)
{
if (_Themes[i].Name == CConfig.Theme)
{
return i;
}
}
return -1;
}
public static string GetThemeScreensPath()
{
string path = String.Empty;
int themeIndex = GetThemeIndex();
if (themeIndex != -1)
{
path = Path.Combine(_Themes[themeIndex].Path, _Themes[themeIndex].SkinFolder);
path = Path.Combine(path, CSettings.sFolderScreens);
}
else
CLog.LogError("Can't find current Theme");
return path;
}
public static STexture GetSkinTexture(string TextureName)
{
int SkinIndex = GetSkinIndex();
if (SkinIndex != -1)
{
for (int i = 0; i < _Skins[SkinIndex].SkinList.Count; i++)
{
SkinElement sk = _Skins[SkinIndex].SkinList[i];
if (sk.Name == TextureName)
{
return sk.Texture;
}
}
}
return new STexture(-1);
}
public static string GetSkinFilePath(string SkinName)
{
return GetSkinFileName(SkinName, GetSkinIndex(), true);
}
private static string GetSkinFileName(string SkinName, int SkinIndex)
{
return GetSkinFileName(SkinName, SkinIndex, false);
}
private static string GetSkinFileName(string SkinName, int SkinIndex, bool ReturnPath)
{
foreach (SkinElement sk in _Skins[SkinIndex].SkinList)
{
if (sk.Name == SkinName)
{
if (!ReturnPath)
return sk.Value;
else
return Path.Combine(_Skins[SkinIndex].Path, sk.Value);
}
}
CLog.LogError("Can't find Skin Element \"" + SkinName);
return SkinName;
}
public static STexture GetSkinVideoTexture(string VideoName)
{
int SkinIndex = GetSkinIndex();
if (SkinIndex != -1)
{
for (int i = 0; i < _Skins[SkinIndex].VideoList.Count; i++)
{
SkinElement sk = _Skins[SkinIndex].VideoList[i];
if (sk.Name == VideoName)
{
float Time = 0f;
if (sk.VideoIndex == -1)
{
sk.VideoIndex = CVideo.VdLoad(GetVideoFilePath(sk.Name));
CVideo.VdSetLoop(sk.VideoIndex, true);
}
CVideo.VdGetFrame(sk.VideoIndex, ref sk.Texture, Time, ref Time);
_Skins[SkinIndex].VideoList[i] = sk;
return sk.Texture;
}
}
}
return new STexture(-1);
}
public static void SkinVideoPause(string VideoName)
{
int SkinIndex = GetSkinIndex();
if (SkinIndex != -1)
{
for (int i = 0; i < _Skins[SkinIndex].VideoList.Count; i++)
{
SkinElement sk = _Skins[SkinIndex].VideoList[i];
if (sk.Name == VideoName)
{
if (sk.VideoIndex == -1)
{
sk.VideoIndex = CVideo.VdLoad(GetVideoFilePath(sk.Name));
CVideo.VdSetLoop(sk.VideoIndex, true);
}
CVideo.VdPause(sk.VideoIndex);
_Skins[SkinIndex].VideoList[i] = sk;
return;
}
}
}
}
public static void SkinVideoResume(string VideoName)
{
int SkinIndex = GetSkinIndex();
if (SkinIndex != -1)
{
for (int i = 0; i < _Skins[SkinIndex].VideoList.Count; i++)
{
SkinElement sk = _Skins[SkinIndex].VideoList[i];
if (sk.Name == VideoName)
{
if (sk.VideoIndex == -1)
{
sk.VideoIndex = CVideo.VdLoad(GetVideoFilePath(sk.Name));
CVideo.VdSetLoop(sk.VideoIndex, true);
}
CVideo.VdResume(sk.VideoIndex);
_Skins[SkinIndex].VideoList[i] = sk;
return;
}
}
}
}
public static string GetVideoFilePath(string VideoName)
{
return GetVideoFileName(VideoName, GetSkinIndex(), true);
}
private static string GetVideoFileName(string VideoName, int SkinIndex)
{
return GetVideoFileName(VideoName, SkinIndex, false);
}
private static string GetVideoFileName(string VideoName, int SkinIndex, bool ReturnPath)
{
foreach (SkinElement sk in _Skins[SkinIndex].VideoList)
{
if (sk.Name == VideoName)
{
if (!ReturnPath)
return sk.Value;
else
return Path.Combine(_Skins[SkinIndex].Path, sk.Value);
}
}
CLog.LogError("Can't find Video Element \"" + VideoName);
return VideoName;
}
#endregion Theme and Skin index handling
#region Element loading
private static void LoadColors(XPathNavigator navigator, int SkinIndex)
{
Skin skin = _Skins[SkinIndex];
List<SColorF> PlayerColors = new List<SColorF>();
float value = 0f;
int i = 1;
while (CHelper.TryGetFloatValueFromXML("//root/Colors/Player" + i.ToString() + "/R", navigator, ref value))
{
SColorF color = new SColorF();
color.R = value;
CHelper.TryGetFloatValueFromXML("//root/Colors/Player" + i.ToString() + "/G", navigator, ref color.G);
CHelper.TryGetFloatValueFromXML("//root/Colors/Player" + i.ToString() + "/B", navigator, ref color.B);
CHelper.TryGetFloatValueFromXML("//root/Colors/Player" + i.ToString() + "/A", navigator, ref color.A);
PlayerColors.Add(color);
i++;
}
skin.ThemeColors.Player = PlayerColors.ToArray();
List<SColorScheme> ColorScheme = new List<SColorScheme>();
List<string> names = CHelper.GetValuesFromXML("ColorSchemes", navigator);
foreach (string str in names)
{
SColorScheme scheme = new SColorScheme();
scheme.Name = str;
CHelper.TryGetFloatValueFromXML("//root/ColorSchemes/" + str + "/R", navigator, ref scheme.Color.R);
CHelper.TryGetFloatValueFromXML("//root/ColorSchemes/" + str + "/G", navigator, ref scheme.Color.G);
CHelper.TryGetFloatValueFromXML("//root/ColorSchemes/" + str + "/B", navigator, ref scheme.Color.B);
CHelper.TryGetFloatValueFromXML("//root/ColorSchemes/" + str + "/A", navigator, ref scheme.Color.A);
ColorScheme.Add(scheme);
}
skin.ThemeColors.ColorSchemes = ColorScheme.ToArray();
_Skins[SkinIndex] = skin;
}
private static void LoadCursor(XPathNavigator navigator, int SkinIndex)
{
string value = String.Empty;
CHelper.GetValueFromXML("//root/Cursor/Skin", navigator, ref Cursor.SkinName, value);
CHelper.TryGetFloatValueFromXML("//root/Cursor/W", navigator, ref Cursor.w);
CHelper.TryGetFloatValueFromXML("//root/Cursor/H", navigator, ref Cursor.h);
if (CHelper.GetValueFromXML("//root/Cursor/Color", navigator, ref value, value))
{
SColorF color = GetColor(value);
Cursor.r = color.R;
Cursor.g = color.G;
Cursor.b = color.B;
Cursor.a = color.A;
Cursor.color = value;
}
else
{
Cursor.color = String.Empty;
CHelper.TryGetFloatValueFromXML("//root/Cursor/R", navigator, ref Cursor.r);
CHelper.TryGetFloatValueFromXML("//root/Cursor/G", navigator, ref Cursor.g);
CHelper.TryGetFloatValueFromXML("//root/Cursor/B", navigator, ref Cursor.b);
CHelper.TryGetFloatValueFromXML("//root/Cursor/A", navigator, ref Cursor.a);
}
}
#endregion Element loading
#region Element Writing
private static void SaveColors(XmlWriter writer, int SkinIndex)
{
writer.WriteStartElement("Colors");
for (int i = 0; i < _Skins[SkinIndex].ThemeColors.Player.Length; i++)
{
writer.WriteStartElement("Player" + (i + 1).ToString());
writer.WriteElementString("R", _Skins[SkinIndex].ThemeColors.Player[i].R.ToString("#0.000"));
writer.WriteElementString("G", _Skins[SkinIndex].ThemeColors.Player[i].G.ToString("#0.000"));
writer.WriteElementString("B", _Skins[SkinIndex].ThemeColors.Player[i].B.ToString("#0.000"));
writer.WriteElementString("A", _Skins[SkinIndex].ThemeColors.Player[i].A.ToString("#0.000"));
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteStartElement("ColorSchemes");
foreach (SColorScheme scheme in _Skins[SkinIndex].ThemeColors.ColorSchemes)
{
writer.WriteStartElement(scheme.Name);
writer.WriteElementString("R", scheme.Color.R.ToString("#0.000"));
writer.WriteElementString("G", scheme.Color.G.ToString("#0.000"));
writer.WriteElementString("B", scheme.Color.B.ToString("#0.000"));
writer.WriteElementString("A", scheme.Color.A.ToString("#0.000"));
writer.WriteEndElement();
}
writer.WriteEndElement();
}
private static void SaveCursor(XmlWriter writer)
{
writer.WriteStartElement("Cursor");
writer.WriteElementString("Skin", Cursor.SkinName);
writer.WriteElementString("W", Cursor.w.ToString("#0.000"));
writer.WriteElementString("H", Cursor.h.ToString("#0.000"));
if (Cursor.color != String.Empty)
{
writer.WriteElementString("Color", Cursor.color);
}
else
{
writer.WriteElementString("R", Cursor.r.ToString("#0.000"));
writer.WriteElementString("G", Cursor.g.ToString("#0.000"));
writer.WriteElementString("B", Cursor.b.ToString("#0.000"));
writer.WriteElementString("A", Cursor.a.ToString("#0.000"));
}
writer.WriteEndElement();
}
#endregion ElementWriting
#region Color Handling
public static SColorF GetColor(string ColorName)
{
SColorF color = new SColorF(1f, 1f, 1f, 1f);
int SkinIndex = GetSkinIndex();
foreach (SColorScheme scheme in _Skins[SkinIndex].ThemeColors.ColorSchemes)
{
if (scheme.Name == ColorName)
{
color.R = scheme.Color.R;
color.G = scheme.Color.G;
color.B = scheme.Color.B;
color.A = scheme.Color.A;
return color;
}
}
return GetPlayerColor(ColorName);
}
public static bool GetColor(string ColorName, int SkinIndex, ref SColorF Color)
{
foreach (SColorScheme scheme in _Skins[SkinIndex].ThemeColors.ColorSchemes)
{
if (scheme.Name == ColorName)
{
Color = new SColorF(scheme.Color);
return true;
}
}
bool success;
GetPlayerColor(ColorName, SkinIndex, out success);
return success;
}
public static SColorF GetPlayerColor(int PlayerNr)
{
SColorF color = new SColorF(1f, 1f, 1f, 1f);
int SkinIndex = GetSkinIndex();
if (_Skins[SkinIndex].ThemeColors.Player.Length < PlayerNr)
return color;
return _Skins[SkinIndex].ThemeColors.Player[PlayerNr - 1];
}
public static SColorF GetPlayerColor(string PlayerNrString)
{
bool dummy;
return GetPlayerColor(PlayerNrString, GetSkinIndex(), out dummy);
}
public static SColorF GetPlayerColor(string PlayerNrString, int SkinIndex, out bool success)
{
SColorF color = new SColorF(1f, 1f, 1f, 1f);
int selection = -1;
for (int i = 0; i < _Skins[SkinIndex].ThemeColors.Player.Length; i++)
{
if (PlayerNrString == "Player" + (i + 1).ToString())
{
selection = i + 1;
break;
}
}
return GetPlayerColor(selection, SkinIndex, out success);
}
public static SColorF GetPlayerColor(int PlayerNr, out bool success)
{
return GetPlayerColor(PlayerNr, GetSkinIndex(), out success);
}
public static SColorF GetPlayerColor(int PlayerNr, int SkinIndex, out bool success)
{
success = false;
SColorF color = new SColorF(1f, 1f, 1f, 1f);
if (_Skins[SkinIndex].ThemeColors.Player.Length < PlayerNr || PlayerNr < 1)
return color;
success = true;
return _Skins[SkinIndex].ThemeColors.Player[PlayerNr - 1];
}
#endregion Color Handling
}
}
+747
View File
@@ -0,0 +1,747 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Base
{
[Flags]
public enum Modifier
{
None,
Shift,
Alt,
Ctrl
}
public struct KeyEvent
{
public bool ModALT;
public bool ModSHIFT;
public bool ModCTRL;
public bool KeyPressed;
public bool Handled;
public Keys Key;
public Char Unicode;
public Modifier Mod;
public KeyEvent(bool alt, bool shift, bool ctrl, bool pressed, char unicode, Keys key)
{
ModALT = alt;
ModSHIFT = shift;
ModCTRL = ctrl;
KeyPressed = pressed;
Unicode = unicode;
Key = key;
Handled = false;
Modifier mALT = Modifier.None;
Modifier mSHIFT = Modifier.None;
Modifier mCTRL = Modifier.None;
if (alt)
mALT = Modifier.Alt;
if (shift)
mSHIFT = Modifier.Shift;
if (ctrl)
mCTRL = Modifier.Ctrl;
if (!alt && !shift && !ctrl)
Mod = Modifier.None;
else
Mod = mALT | mSHIFT | mCTRL;
}
}
public struct MouseEvent
{
public int X;
public int Y;
public bool LB; //left button click
public bool RB; //right button click
public bool LBH; //left button hold (when moving)
public bool RBH; //right button hold (when moving)
public bool ModALT;
public bool ModSHIFT;
public bool ModCTRL;
public Modifier Mod;
public int Wheel;
public MouseEvent(bool alt, bool shift, bool ctrl, int x, int y, bool lb, bool rb, int wheel, bool lbh, bool rbh)
{
X = x;
Y = y;
LB = lb;
RB = rb;
LBH = lbh;
RBH = rbh;
ModALT = alt;
ModSHIFT = shift;
ModCTRL = ctrl;
Modifier mALT = Modifier.None;
Modifier mSHIFT = Modifier.None;
Modifier mCTRL = Modifier.None;
if (alt)
mALT = Modifier.Alt;
if (shift)
mSHIFT = Modifier.Shift;
if (ctrl)
mCTRL = Modifier.Ctrl;
if (!alt && !shift && !ctrl)
Mod = Modifier.None;
else
Mod = mALT | mSHIFT | mCTRL;
Wheel = wheel;
}
}
static class CTime
{
private static Stopwatch _Stopwatch = new Stopwatch();
private static float _fps = 0.0f;
private static long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
public static void Reset()
{
_Stopwatch.Reset();
}
public static void Start()
{
_Stopwatch.Start();
}
public static void Restart()
{
Reset();
Start();
}
public static bool IsRunning()
{
return _Stopwatch.IsRunning;
}
public static float GetMilliseconds()
{
if (_Stopwatch.IsRunning)
{
if (Stopwatch.IsHighResolution)
return (float)(((double)nanosecPerTick * (double)_Stopwatch.ElapsedTicks) / (1000.0 * 1000.0));
else
return (float)_Stopwatch.ElapsedMilliseconds;
}
else
return 0f;
}
public static float CalculateFPS()
{
float ms = GetMilliseconds();
if (ms > 0)
{
_fps = 1 / ms;
}
return _fps * 1000f;
}
public static double GetFPS()
{
return _fps * 1000f;
}
}
class CKeys
{
private List<KeyEvent> _KeysPool;
private List<KeyEvent> _ActualPool;
private Object _CopyLock = new Object();
private bool _ModALT;
private bool _ModCTRL;
private bool _ModSHIFT;
private bool _KeyPressed;
private Keys _Keys;
private Char _char;
private System.Diagnostics.Stopwatch _timer;
public CKeys()
{
_ModALT = false;
_ModCTRL = false;
_ModSHIFT = false;
_char = ' ';
_KeyPressed = false;
_Keys = Keys.D0;
_KeysPool = new List<KeyEvent>();
_ActualPool = new List<KeyEvent>();
_timer = new System.Diagnostics.Stopwatch();
}
private void Add(bool alt, bool shift, bool ctrl, bool pressed, char unicode, Keys key)
{
bool KeyRepeat = false;
if ((_char == unicode) && _KeyPressed)
KeyRepeat = true;
else if (_Keys == key)
KeyRepeat = true;
if (!_timer.IsRunning || (_timer.ElapsedMilliseconds > 75) || !KeyRepeat)
{
KeyEvent pool = new KeyEvent(alt, shift, ctrl, pressed && (unicode != Char.MinValue), unicode, key);
lock (_CopyLock)
{
try
{
_KeysPool.Add(pool);
}
catch (Exception)
{
}
}
_timer.Reset();
_timer.Start();
}
}
private void Del(int index)
{
_ActualPool.RemoveAt(index);
}
private void CheckModifiers()
{
Keys keys = Control.ModifierKeys;
_ModSHIFT = ((keys & Keys.Shift) == Keys.Shift);
_ModALT = ((keys & Keys.Alt) == Keys.Alt);
_ModCTRL = ((keys & Keys.Control) == Keys.Control);
}
public void KeyDown(KeyEventArgs e)
{
CheckModifiers();
bool Repeat = false;
if (_Keys == e.KeyCode)
Repeat = true;
if (!_timer.IsRunning || (_timer.ElapsedMilliseconds > 75) || !Repeat)
{
_Keys = e.KeyCode;
if (Repeat)
Add(_ModALT, _ModSHIFT, _ModCTRL, _KeyPressed, _char, _Keys);
else
Add(_ModALT, _ModSHIFT, _ModCTRL, _KeyPressed, Char.MinValue, _Keys);
}
}
public void KeyPress(KeyPressEventArgs e)
{
CheckModifiers();
Add(_ModALT, _ModSHIFT, _ModCTRL, true, e.KeyChar, Keys.None);
_char = e.KeyChar;
_KeyPressed = true;
}
public void KeyUp(KeyEventArgs e)
{
CheckModifiers();
_KeyPressed = false;
}
public bool PollEvent(ref KeyEvent KeyEvent)
{
if (_ActualPool.Count > 0)
{
KeyEvent = _ActualPool[0];
Del(0);
return true;
}
else return false;
}
public void CopyEvents()
{
lock (_CopyLock)
{
foreach (KeyEvent e in _KeysPool)
{
_ActualPool.Add(e);
}
_KeysPool.Clear();
}
}
}
class CMouse
{
private List<MouseEvent> _EventsPool;
private List<MouseEvent> _ActualPool;
private int _x = 0;
private int _y = 0;
private Object _CopyLock = new Object();
private bool _ModALT;
private bool _ModCTRL;
private bool _ModSHIFT;
private System.Diagnostics.Stopwatch _timer;
public int X
{
get { return _x; }
}
public int Y
{
get { return _y; }
}
public bool Visible = false;
public CMouse()
{
_ModALT = false;
_ModCTRL = false;
_ModSHIFT = false;
_EventsPool = new List<MouseEvent>();
_ActualPool = new List<MouseEvent>();
_timer = new System.Diagnostics.Stopwatch();
}
private void Add(bool alt, bool shift, bool ctrl, int x, int y, bool lb, bool rb, int wheel, bool lbh, bool rbh)
{
x = (int)((float)x * (float)CSettings.iRenderW / (float)CDraw.GetScreenWidth());
y = (int)((float)y * (float)CSettings.iRenderH / (float)CDraw.GetScreenHeight());
MouseEvent pool = new MouseEvent(alt, shift, ctrl, x, y, lb, rb, -wheel/120, lbh, rbh);
lock (_CopyLock)
{
_EventsPool.Add(pool);
}
_x = x;
_y = y;
_timer.Reset();
_timer.Start();
}
private void Del(int index)
{
_ActualPool.RemoveAt(index);
}
private void CheckModifiers()
{
Keys keys = Control.ModifierKeys;
_ModSHIFT = ((keys & Keys.Shift) == Keys.Shift);
_ModALT = ((keys & Keys.Alt) == Keys.Alt);
_ModCTRL = ((keys & Keys.Control) == Keys.Control);
}
public void MouseMove(MouseEventArgs e)
{
CheckModifiers();
Add(_ModALT, _ModSHIFT, _ModCTRL, e.X, e.Y, false, false, e.Delta, e.Button == MouseButtons.Left, e.Button == MouseButtons.Right);
}
public void MouseWheel(MouseEventArgs e)
{
CheckModifiers();
Add(_ModALT, _ModSHIFT, _ModCTRL, e.X, e.Y, false, false, e.Delta, e.Button == MouseButtons.Left, e.Button == MouseButtons.Right);
}
public void MouseDown(MouseEventArgs e)
{
CheckModifiers();
Add(_ModALT, _ModSHIFT, _ModCTRL, e.X, e.Y, e.Button == MouseButtons.Left, e.Button == MouseButtons.Right, e.Delta, false, false);
}
public void MouseUp(MouseEventArgs e)
{
//CheckModifiers();
//Add(_ModALT, _ModSHIFT, _ModCTRL, e.X, e.Y, e.Button == MouseButtons.Left, e.Button == MouseButtons.Right, e.Delta);
}
public bool PollEvent(ref MouseEvent MouseEvent)
{
if (_ActualPool.Count > 0)
{
MouseEvent = _ActualPool[0];
Del(0);
return true;
}
else return false;
}
public void CopyEvents()
{
lock (_CopyLock)
{
foreach (MouseEvent e in _EventsPool)
{
_ActualPool.Add(e);
}
_EventsPool.Clear();
}
}
}
class CHelper
{
public static int TryReadInt(StreamReader sr)
{
char chr = '0';
string value = String.Empty;
try
{
chr = (char)sr.Peek();
while ((chr.CompareTo(' ') != 0) && ((int)chr != 19) && ((int)chr != 16) && ((int)chr != 13))
{
chr = (char)sr.Read();
value += chr.ToString();
chr = (char)sr.Peek();
}
}
catch (Exception)
{
return 0;
}
int result = 0;
int.TryParse(value, out result);
return result;
}
public static void SetRect(RectangleF Bounds, ref RectangleF Rect, float RectAspect, EAspect Aspect)
{
float rW = Bounds.Right - Bounds.Left;
float rH = Bounds.Bottom - Bounds.Top;
float rA = rW / rH;
float ScaledWidth = rW;
float ScaledHeight = rH;
switch (Aspect)
{
case EAspect.Crop:
if (rA >= RectAspect)
{
ScaledWidth = rW;
ScaledHeight = rH * rA / RectAspect;
}
else
{
ScaledHeight = rH;
ScaledWidth = rW * RectAspect / rA;
}
break;
case EAspect.LetterBox:
if (RectAspect >= 1)
{
ScaledWidth = rW;
ScaledHeight = rH * rA / RectAspect;
}
else
{
ScaledHeight = rH;
ScaledWidth = rW * RectAspect / rA;
}
break;
default:
ScaledWidth = rW;
ScaledHeight = rH;
break;
}
float Left = (rW - ScaledWidth) / 2 + Bounds.Left;
float Rigth = Left + ScaledWidth;
float Upper = (rH - ScaledHeight) / 2 + Bounds.Top;
float Lower = Upper + ScaledHeight;
Rect = new RectangleF(Left, Upper, Rigth - Left, Lower - Upper);
}
public static bool TryGetEnumValueFromXML<T>(string Cast, XPathNavigator Navigator, ref T value)
where T : struct
{
string val = String.Empty;
if (GetValueFromXML(Cast, Navigator, ref val, Enum.GetName(typeof(T), value)))
{
TryParse<T>(val, out value, true);
return true;
}
return false;
}
public static bool TryGetIntValueFromXML(string Cast, XPathNavigator Navigator, ref int value)
{
string val = String.Empty;
if (GetValueFromXML(Cast, Navigator, ref val, value.ToString()))
{
int res = 0;
if (int.TryParse(val, out res))
{
value = res;
return true;
}
}
return false;
}
public static bool TryGetFloatValueFromXML(string Cast, XPathNavigator Navigator, ref float value)
{
string val = String.Empty;
if (GetValueFromXML(Cast, Navigator, ref val, value.ToString()))
{
float res = 0;
if (TryParse(val, out res))
{
value = res;
return true;
}
}
return false;
}
public static bool GetValueFromXML(string Cast, XPathNavigator Navigator, ref string Value, string DefaultValue)
{
XPathNodeIterator iterator;
int results = 0;
string val = string.Empty;
try
{
Navigator.MoveToFirstChild();
iterator = Navigator.Select(Cast);
while (iterator.MoveNext())
{
val = iterator.Current.Value;
results++;
}
}
catch (Exception)
{
results = 0;
}
if ((results == 0) || (results > 1))
{
Value = DefaultValue;
return false;
}
else
{
Value = val;
return true;
}
}
public static List<string> GetValuesFromXML(string Cast, XPathNavigator Navigator)
{
List<string> values = new List<string>();
try
{
Navigator.MoveToRoot();
Navigator.MoveToFirstChild();
Navigator.MoveToFirstChild();
while (Navigator.Name != Cast)
Navigator.MoveToNext();
Navigator.MoveToFirstChild();
values.Add(Navigator.LocalName);
while(Navigator.MoveToNext())
values.Add(Navigator.LocalName);
}
catch (Exception)
{
}
return values;
}
public static bool ItemExistsInXML(string Cast, XPathNavigator Navigator)
{
XPathNodeIterator iterator;
int results = 0;
try
{
Navigator.MoveToFirstChild();
iterator = Navigator.Select(Cast);
while (iterator.MoveNext())
results++;
}
catch (Exception)
{
results = 0;
}
if (results == 0)
return false;
return true;
}
public List<string> ListFiles(string path, string cast)
{
return ListFiles(path, cast, false, false);
}
public List<string> ListFiles(string path, string cast, bool recursive)
{
return ListFiles(path, cast, recursive, false);
}
public List<string> ListFiles(string path, string cast, bool recursive, bool fullpath)
{
List<string> files = new List<string>();
DirectoryInfo dir = new DirectoryInfo(path);
try
{
foreach (FileInfo file in dir.GetFiles(cast))
{
if (!fullpath)
files.Add(file.Name);
else
//files.Add(Path.Combine(file.DirectoryName, file.Name));
files.Add(file.FullName);
}
if (recursive)
{
foreach (DirectoryInfo di in dir.GetDirectories())
{
files.AddRange(ListFiles(di.FullName, cast, recursive, fullpath));
}
}
} catch (Exception)
{
}
return files;
}
public static bool TryParse<T>(string value, out T result)
where T : struct
{
return TryParse<T>(value, out result, false);
}
public static bool TryParse<T>(string value, out T result, bool ignoreCase)
where T : struct
{
result = default(T);
try
{
result = (T)Enum.Parse(typeof(T), value, ignoreCase);
return true;
}
catch { }
return false;
}
public static bool TryParse(string value, out float result)
{
value = value.Replace(',', '.');
return float.TryParse(value, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo, out result);
}
public static bool IsInBounds(SRectF bounds, MouseEvent MouseEvent)
{
return IsInBounds(bounds, MouseEvent.X, MouseEvent.Y);
}
public static bool IsInBounds(SRectF bounds, int x, int y)
{
return ((bounds.X <= x) && (bounds.X + bounds.W >= x) && (bounds.Y <= y) && (bounds.Y + bounds.H >= y));
}
}
static class CEncoding
{
public static Encoding GetEncoding(string EncodingName)
{
switch (EncodingName)
{
case "AUTO":
return Encoding.Default;
case "CP1250":
return Encoding.GetEncoding(1250);
case "CP1252":
return Encoding.GetEncoding(1252);
case "LOCALE":
return Encoding.Default;
case "UTF8":
return Encoding.UTF8;
default:
return Encoding.UTF8;
}
}
public static string GetEncodingName(Encoding Enc)
{
string Result = "UTF8";
if (Enc.CodePage == 1250)
Result = "CP1250";
if (Enc.CodePage == 1252)
Result = "CP1252";
return Result;
}
}
}
+98
View File
@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Video;
namespace Vocaluxe.Base
{
static class CVideo
{
#region VideoDecoder
private static IVideoDecoder _VideoDecoder;
#region Init
public static void Init()
{
switch (CConfig.VideoDecoder)
{
case EVideoDecoder.FFmpeg:
_VideoDecoder = new CVideoDecoderFFmpeg();
break;
default:
_VideoDecoder = new CVideoDecoderFFmpeg();
break;
}
_VideoDecoder.Init();
}
#endregion Init
#region Interface
public static bool VdInit()
{
return _VideoDecoder.Init();
}
public static void VdCloseAll()
{
_VideoDecoder.CloseAll();
}
public static int GetNumStreams()
{
return _VideoDecoder.GetNumStreams();
}
public static int VdLoad(string VideoFileName)
{
return _VideoDecoder.Load(VideoFileName);
}
public static bool VdClose(int StreamID)
{
return _VideoDecoder.Close(StreamID);
}
public static float VdGetLength(int StreamID)
{
return _VideoDecoder.GetLength(StreamID);
}
public static bool VdGetFrame(int StreamID, ref STexture Frame, float Time, ref float VideoTime)
{
return _VideoDecoder.GetFrame(StreamID, ref Frame, Time, ref VideoTime);
}
public static bool VdSkip(int StreamID, float Start, float Gap)
{
return _VideoDecoder.Skip(StreamID, Start, Gap);
}
public static void VdSetLoop(int StreamID, bool Loop)
{
_VideoDecoder.SetLoop(StreamID, Loop);
}
public static void VdPause(int StreamID)
{
_VideoDecoder.Pause(StreamID);
}
public static void VdResume(int StreamID)
{
_VideoDecoder.Resume(StreamID);
}
public static bool VdFinished(int StreamID)
{
return _VideoDecoder.Finished(StreamID);
}
#endregion Interface
#endregion VideoDecoder
}
}
+116
View File
@@ -0,0 +1,116 @@
Vocaluxe Roadmap
-------------------------------------------------------------
- v0.0.1 (reached: 10.05.2011):
- Graphic system: OpenGL and WinForm
- Keyboard Input
- Config System
- Menu System
- Theme System
- Built in Theme-Editor
- Audio Playback (BASS)
- v0.0.2 (reached: 20.05.2011):
- Screen Fading
- Menu Navigation
- Mouse Input
- v0.0.3 (reached: 03.06.2011):
- Song Loading (Header)
- Song Screen
- v0.0.4 (reached: 04.07.2011):
- Audio Input (BASS)
- Pitch Detection
- Font System
- Song Loading (Notes)
- v0.0.5 (reached: 21.08.2011):
- Video Playback
- Menu Background Video
- Sing Screen
- Score System
- v0.0.6 (reached: 08.09.2011):
- Audio Input Update
- Option Screens:
* Game
* Sound
* Record
* Video
* Player
- Log System
- Duet (basic support)
- v0.0.7 (reached: 07.11.2011):
- Linebonus
- Perfect Note
- Golden Notes
- Lyric Helper
- Multiple Edition, Genre and Language tag Support
- Player Profiles
- Statistics (Highscore-DB)
- Language System (english)
- Auto mic gap function (in record screen)
- v0.0.8 (reached: 13.12.2011):
- Search Function
- Random Song Function
- Player Selection Screen
- Player Profiles
- v0.0.9 (reached: 24.01.2012):
- Lyric Fading
- Theme System Update
- Language System (german, french)
- Command Line Parameters
- Assign mics to player 1 and 2 automatically (if there is no mic config)
- Direct3D support
- OpenAL Playback (alpha)
- NAudio Playback (beta)
- PortAudio Record and Playback
-------------------------------------------------------------
+ v0.1.0:
- Theme System Update
- A nicer Theme!
+ v0.2.0:
- Menu Background Music
- Medley
- WiiMote Support
- OnScreen Keyboard?
- Kinect Support?
+ v0.3.0:
- Song Editor
- Help System
- Duet (full support)
- Mark newly added songs
- Playlist-Support
- Theme System Update (Theme Editor)
+ v0.4.0:
- Challenge Mode (with more than 2 player at once)
+ v0.5.0:
- Party Mode: Team-Battle
- Party Mode: Tic, Tac, Toe
- Party Mode: 4 in a row
+ v0.6.0:
- Jukebox
+ v0.7.0:
- Tournament Mode
+ v0.8.0:
- Party Mode: Casting Show
+ v0.9.0:
- ?
+ v1.0.0:
- ?
Binary file not shown.
+215
View File
@@ -0,0 +1,215 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Base;
using Vocaluxe.Lib.Song;
namespace Vocaluxe.GameModes
{
class CPoints
{
private SPlayer[,] _Rounds;
public CPoints(int NumRounds, SPlayer[] Player)
{
_Rounds = new SPlayer[NumRounds, Player.Length];
for (int round = 0; round < NumRounds; round++)
{
for (int player = 0; player < Player.Length; player++)
{
_Rounds[round, player].ProfileID = Player[player].ProfileID;
_Rounds[round, player].Name = Player[player].Name;
_Rounds[round, player].Difficulty = Player[player].Difficulty;
_Rounds[round, player].Points = 0;
_Rounds[round, player].Medley = false;
_Rounds[round, player].Duet = false;
_Rounds[round, player].SongFinished = false;
}
}
}
public void SetPoints(int Round, int SongID, SPlayer[] Player, bool Medley, bool Duet)
{
long DateTicks = DateTime.Now.Ticks;
for (int player = 0; player < Player.Length; player++)
{
_Rounds[Round, player].SongID = SongID;
_Rounds[Round, player].LineNr = Player[player].LineNr;
_Rounds[Round, player].Points = Player[player].Points;
_Rounds[Round, player].Medley = Medley;
_Rounds[Round, player].Duet = Duet;
_Rounds[Round, player].DateTicks = DateTicks;
_Rounds[Round, player].SongFinished = Player[player].SongFinished;
}
}
public int NumRounds
{
get { return _Rounds.GetLength(0); }
}
public int NumPlayer
{
get { return _Rounds.GetLength(1); }
}
public SPlayer[] GetPlayer(int Round, int numPlayer)
{
if (NumPlayer == 0)
return new SPlayer[1];
if (Round >= NumRounds)
return new SPlayer[1];
SPlayer[] player = new SPlayer[numPlayer];
for (int p = 0; p < player.Length; p++)
{
player[p].Name = _Rounds[Round, p].Name;
player[p].Points = _Rounds[Round, p].Points;
player[p].SongID = _Rounds[Round, p].SongID;
player[p].LineNr = _Rounds[Round, p].LineNr;
player[p].Difficulty = _Rounds[Round, p].Difficulty;
player[p].Medley = _Rounds[Round, p].Medley;
player[p].Duet = _Rounds[Round, p].Duet;
player[p].DateTicks = _Rounds[Round, p].DateTicks;
player[p].SongFinished = _Rounds[Round, p].SongFinished;
player[p].ProfileID = _Rounds[Round, p].ProfileID;
}
return player;
}
}
abstract class CGameMode : IGameMode
{
protected bool _Initialized = false;
protected EGameMode _GameMode;
protected List<int> _SongIDs;
protected int _ActualSong;
protected CPoints _Points;
#region Implementation
public virtual void Init()
{
_SongIDs = new List<int>();
Reset();
}
public virtual EGameMode GetGameMode()
{
return _GameMode;
}
public virtual bool AddVisibleSong(int VisibleIndex)
{
if (CSongs.VisibleSongs.Length > VisibleIndex)
{
//int ID = CSongs.VisibleSongs[VisibleIndex].ID;
//if (!_SongIDs.Exists(delegate(int i) { return (i == ID); }))
//{
_SongIDs.Add(CSongs.VisibleSongs[VisibleIndex].ID);
return true;
//}
}
return false;
}
public virtual bool AddSong(int AbsoluteIndex)
{
if (CSongs.AllSongs.Length > AbsoluteIndex)
{
//int ID = CSongs.AllSongs[AbsoluteIndex].ID;
//if (!_SongIDs.Exists(delegate(int i) { return (i == ID); }))
//{
_SongIDs.Add(CSongs.AllSongs[AbsoluteIndex].ID);
return true;
//}
}
return false;
}
public virtual bool RemoveVisibleSong(int VisibleIndex)
{
if (CSongs.VisibleSongs.Length > VisibleIndex)
{
return _SongIDs.Remove(CSongs.VisibleSongs[VisibleIndex].ID);
}
return false;
}
public virtual bool RemoveSong(int AbsoluteIndex)
{
if (CSongs.AllSongs.Length > AbsoluteIndex)
{
return _SongIDs.Remove(CSongs.AllSongs[AbsoluteIndex].ID);
}
return false;
}
public virtual void ClearSongs()
{
_SongIDs.Clear();
}
public virtual void Reset()
{
_ActualSong = -1;
}
public virtual void Start(SPlayer[] Player)
{
_Points = new CPoints(_SongIDs.Count, Player);
}
public virtual void NextRound(SPlayer[] Player)
{
if (_ActualSong < _SongIDs.Count && _SongIDs.Count > 0)
{
if (_ActualSong > -1)
{
_Points.SetPoints(_ActualSong, _SongIDs[_ActualSong], Player, _GameMode == EGameMode.Medley, _GameMode == EGameMode.Duet);
}
_ActualSong++;
}
}
public virtual bool IsFinished()
{
return (_ActualSong == _SongIDs.Count || _SongIDs.Count == 0);
}
public virtual int GetActualRoundNr()
{
return _ActualSong + 1;
}
public virtual CSong GetSong()
{
if (_ActualSong >= 0 && _ActualSong < _SongIDs.Count)
{
return CSongs.GetSong(_SongIDs[_ActualSong]);
}
return null;
}
public virtual int GetNumSongs()
{
return _SongIDs.Count;
}
public virtual CSong GetSong(int Num)
{
if (Num - 1 < _SongIDs.Count)
return CSongs.GetSong(_SongIDs[Num - 1]);
return null;
}
public virtual CPoints GetPoints()
{
return _Points;
}
#endregion Implementation
}
}
+17
View File
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.GameModes
{
class CGameModeDuet : CGameMode
{
public override void Init()
{
base.Init();
_GameMode = EGameMode.Duet;
_Initialized = true;
}
}
}
+17
View File
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.GameModes
{
class CGameModeMedley : CGameMode
{
public override void Init()
{
base.Init();
_GameMode = EGameMode.Medley;
_Initialized = true;
}
}
}
+17
View File
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.GameModes
{
class CGameModeNormal : CGameMode
{
public override void Init()
{
base.Init();
_GameMode = EGameMode.Normal;
_Initialized = true;
}
}
}
+40
View File
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Base;
using Vocaluxe.Lib.Song;
namespace Vocaluxe.GameModes
{
public enum EGameMode
{
Normal,
Medley,
Duet
}
interface IGameMode
{
void Init();
EGameMode GetGameMode();
bool AddVisibleSong(int VisibleIndex);
bool AddSong(int AbsoluteIndex);
bool RemoveVisibleSong(int VisibleIndex);
bool RemoveSong(int AbsoluteIndex);
void ClearSongs();
void Reset();
void Start(SPlayer[] Player);
void NextRound(SPlayer[] Player);
bool IsFinished();
int GetActualRoundNr();
CSong GetSong();
CPoints GetPoints();
int GetNumSongs();
CSong GetSong(int Num);
}
}
+996
View File
@@ -0,0 +1,996 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Base;
using Vocaluxe.Menu;
using System.Drawing;
using SlimDX;
using SlimDX.Direct3D9;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using SlimDX.Windows;
namespace Vocaluxe.Lib.Draw
{
class CDirect3D : Form, IDraw
{
#region private vars
private CKeys _Keys;
private CMouse _Mouse;
private bool _Run;
private Direct3D _D3D;
private Device _Device;
private PresentParameters _PresentParameters;
private bool _fullscreen = false;
private Size _OldSize;
private Size _SizeBeforeMinimize;
private List<STexture> _Textures;
private List<Texture> _D3DTextures;
private VertexBuffer _VertexBuffer;
private int h = 1;
private int w = 1;
private int y = 0;
private int x = 0;
private Bitmap blankMap;
private STexture blankTexture;
#endregion private vars
public CDirect3D()
{
this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon));
_Textures = new List<STexture>();
_D3DTextures = new List<Texture>();
_Keys = new CKeys();
_D3D = new Direct3D();
this.Paint += new PaintEventHandler(this.OnPaintEvent);
this.Closing += new CancelEventHandler(this.OnClosingEvent);
this.Resize += new EventHandler(this.OnResizeEvent);
this.KeyDown += new KeyEventHandler(this.OnKeyDown);
this.PreviewKeyDown += new PreviewKeyDownEventHandler(this.OnPreviewKeyDown);
this.KeyPress += new KeyPressEventHandler(this.OnKeyPress);
this.KeyUp += new KeyEventHandler(this.OnKeyUp);
_Mouse = new CMouse();
this.MouseMove += new MouseEventHandler(this.OnMouseMove);
this.MouseWheel += new MouseEventHandler(this.OnMouseWheel);
this.MouseDown += new MouseEventHandler(this.OnMouseDown);
this.MouseUp += new MouseEventHandler(this.OnMouseUp);
this.MouseLeave += new EventHandler(this.OnMouseLeave);
this.MouseEnter += new EventHandler(this.OnMouseEnter);
this.ClientSize = new Size(CConfig.ScreenW, CConfig.ScreenH);
_SizeBeforeMinimize = ClientSize;
_PresentParameters = new PresentParameters();
_PresentParameters.Windowed = true;
_PresentParameters.SwapEffect = SwapEffect.Discard;
_PresentParameters.BackBufferHeight = CConfig.ScreenH;
_PresentParameters.BackBufferWidth = CConfig.ScreenW;
_PresentParameters.BackBufferFormat = _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format;
_PresentParameters.Multisample = MultisampleType.None;
_PresentParameters.MultisampleQuality = 0;
int quality = 0;
if (CConfig.AAMode == EAntiAliasingModes.x0)
{
_PresentParameters.Multisample = MultisampleType.None;
_PresentParameters.MultisampleQuality = quality;
}
else if (CConfig.AAMode == EAntiAliasingModes.x2)
{
if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.TwoSamples, out quality))
{
_PresentParameters.Multisample = MultisampleType.TwoSamples;
_PresentParameters.MultisampleQuality = quality - 1;
}
else
CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
}
else if (CConfig.AAMode == EAntiAliasingModes.x4)
{
if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.FourSamples, out quality))
{
_PresentParameters.Multisample = MultisampleType.FourSamples;
_PresentParameters.MultisampleQuality = quality - 1;
}
else
CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
}
else if (CConfig.AAMode == EAntiAliasingModes.x8)
{
if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.EightSamples, out quality))
{
_PresentParameters.Multisample = MultisampleType.EightSamples;
_PresentParameters.MultisampleQuality = quality - 1;
}
else
CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
}
else if (CConfig.AAMode == EAntiAliasingModes.x16 || CConfig.AAMode == EAntiAliasingModes.x32) //x32 is not supported, fallback to x16
{
if (_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, MultisampleType.SixteenSamples, out quality))
{
_PresentParameters.Multisample = MultisampleType.SixteenSamples;
_PresentParameters.MultisampleQuality = quality - 1;
}
else
CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA");
}
if(CConfig.VSync == EOffOn.TR_CONFIG_ON)
_PresentParameters.PresentationInterval = PresentInterval.Default;
else
_PresentParameters.PresentationInterval = PresentInterval.Immediate;
Capabilities caps = _D3D.GetDeviceCaps(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware);
CreateFlags flags = CreateFlags.None;
if ((caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
flags = CreateFlags.HardwareVertexProcessing;
else
flags = CreateFlags.SoftwareVertexProcessing;
_Device = new Device(_D3D, _D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, Handle, flags, _PresentParameters);
this.CenterToScreen();
blankMap = new Bitmap(1, 1); //Quick and Dirty, used for DrawColor
Graphics g = Graphics.FromImage(blankMap);
g.Clear(Color.White);
g.Dispose();
blankTexture = AddTexture(blankMap);
h = ClientSize.Height;
w = ClientSize.Width;
blankMap.Dispose();
}
#region form events
private void OnPaintEvent(object sender, PaintEventArgs e)
{
}
private void OnResizeEvent(object sender, EventArgs e)
{
}
private void OnClosingEvent(object sender, CancelEventArgs e)
{
_Run = false;
}
protected override void OnLoad(EventArgs e)
{
_Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
this.ClientSize = this.ClientSize;
RResize();
}
#endregion form events
private void RResize()
{
if (ClientSize.Width == 0 || ClientSize.Height == 0)
{
ClientSize = _SizeBeforeMinimize;
}
if (_Run)
{
h = ClientSize.Height;
w = ClientSize.Width;
y = 0;
x = 0;
if ((float)w / (float)h > CSettings.GetRenderAspect())
{
w = (int)Math.Round((float)h * CSettings.GetRenderAspect());
x = (ClientSize.Width - w) / 2;
}
else
{
h = (int)Math.Round((float)w / CSettings.GetRenderAspect());
y = (ClientSize.Height - h) / 2;
}
_PresentParameters.BackBufferWidth = ClientSize.Width;
_PresentParameters.BackBufferHeight = ClientSize.Height;
ClearScreen();
Reset();
Init();
_Device.Viewport = new Viewport(x, y, w, h);
_SizeBeforeMinimize = ClientSize;
}
}
private void EnterFullScreen()
{
_OldSize = this.ClientSize;
this.ClientSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
this.FormBorderStyle = FormBorderStyle.None;
CenterToScreen();
_fullscreen = true;
CConfig.FullScreen = EOffOn.TR_CONFIG_ON;
RResize();
Cursor.Hide();
_Mouse.Visible = true;
CConfig.SaveConfig();
}
private void LeaveFullScreen()
{
this.ClientSize = _OldSize;
this.FormBorderStyle = FormBorderStyle.Sizable;
CenterToScreen();
_fullscreen = false;
CConfig.FullScreen = EOffOn.TR_CONFIG_OFF;
Cursor.Hide();
_Mouse.Visible = true;
CConfig.SaveConfig();
}
#region mouse event handlers
private void OnMouseMove(object sender, MouseEventArgs e)
{
_Mouse.MouseMove(e);
}
private void OnMouseWheel(object sender, MouseEventArgs e)
{
_Mouse.MouseWheel(e);
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
_Mouse.MouseDown(e);
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
_Mouse.MouseUp(e);
}
private void OnMouseLeave(object sender, EventArgs e)
{
_Mouse.Visible = false;
Cursor.Show();
}
private void OnMouseEnter(object sender, EventArgs e)
{
Cursor.Hide();
_Mouse.Visible = true;
}
#endregion
#region keyboard event handlers
private void OnPreviewKeyDown(object sender, System.Windows.Forms.PreviewKeyDownEventArgs e)
{
OnKeyDown(sender, new KeyEventArgs(e.KeyData));
}
private void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
_Keys.KeyDown(e);
}
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
_Keys.KeyPress(e);
}
private void OnKeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
_Keys.KeyUp(e);
}
#endregion keyboard event handlers
#region implementation
public bool Init()
{
this.Text = CSettings.GetFullVersionText();
Matrix translate = Matrix.Translation(new Vector3(-CSettings.iRenderW / 2, CSettings.iRenderH / 2, 0));
Matrix projection = Matrix.OrthoOffCenterLH(-CSettings.iRenderW / 2, CSettings.iRenderW / 2, -CSettings.iRenderH / 2, CSettings.iRenderH / 2, CSettings.zNear, CSettings.zFar);
_VertexBuffer = new VertexBuffer(_Device, 4 * Marshal.SizeOf(typeof(TexturedColoredVertex)), Usage.WriteOnly | Usage.Dynamic, VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Diffuse, Pool.Default);
_Device.SetStreamSource(0, _VertexBuffer, 0, Marshal.SizeOf(typeof(TexturedColoredVertex)));
_Device.VertexDeclaration = TexturedColoredVertex.GetDeclaration(_Device);
_Device.SetTransform(TransformState.Projection, projection);
_Device.SetTransform(TransformState.World, translate);
_Device.SetRenderState(RenderState.CullMode, Cull.None);
_Device.SetRenderState(RenderState.AlphaBlendEnable, true);
_Device.SetRenderState(RenderState.Lighting, false);
_Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
_Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
if(_PresentParameters.Multisample != MultisampleType.None)
_Device.SetRenderState(RenderState.MultisampleAntialias, true);
_Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear);
_Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear);
_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear);
_Device.SetSamplerState(0, SamplerState.AddressU, TextureAddress.Clamp);
_Device.SetSamplerState(0, SamplerState.AddressV, TextureAddress.Clamp);
_Device.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture);
_Device.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse);
_Device.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate);
return true;
}
public void MainLoop()
{
_Run = true;
int delay = 0;
this.Show();
if (CConfig.FullScreen == EOffOn.TR_CONFIG_ON)
{
CSettings.bFullScreen = true;
EnterFullScreen();
}
while (_Run)
{
Application.DoEvents();
if (_Run)
{
ClearScreen();
_Device.BeginScene();
_Run = _Run && CGraphics.Draw();
_Run = CGraphics.UpdateGameLogic(_Keys, _Mouse);
_Device.EndScene();
try
{
_Device.Present();
}
catch (Direct3D9Exception e)
{
if (_Device.TestCooperativeLevel() == ResultCode.DeviceNotReset) //Do only reset when the device in a resetable state!
{
Reset();
Init();
}
}
if ((CSettings.bFullScreen && !_fullscreen) || (!CSettings.bFullScreen && _fullscreen))
{
if (!_fullscreen)
EnterFullScreen();
else
LeaveFullScreen();
}
if (CTime.IsRunning())
delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds());
if (delay >= 1)
System.Threading.Thread.Sleep(delay);
CTime.CalculateFPS();
CTime.Restart();
}
else
this.Close();
}
}
public void Reset()
{
TexturedColoredVertex.GetDeclaration(_Device).Dispose();
_VertexBuffer.Dispose();
_Device.Reset(_PresentParameters);
}
public bool Unload()
{
for (int i = 0; i < _D3DTextures.Count; i++)
{
_D3DTextures[i].Dispose();
}
TexturedColoredVertex.GetDeclaration(_Device).Dispose();
_VertexBuffer.Dispose();
_Device.Dispose();
_D3D.Dispose();
return true;
}
public int GetScreenWidth()
{
return _Device.Viewport.Width;
}
public int GetScreenHeight()
{
return _Device.Viewport.Height;
}
public RectangleF GetTextBounds(CText text)
{
return GetTextBounds(text, text.Height);
}
public RectangleF GetTextBounds(CText text, float Height)
{
CFonts.Height = Height;
CFonts.SetFont(text.Fon);
CFonts.Style = text.Style;
return new RectangleF(text.X, text.Y, CFonts.GetTextWidth(CLanguage.Translate(text.Text)), CFonts.GetTextHeight(text.Text));
}
#region Basic Draw Methods
public void ClearScreen()
{
_Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
}
public STexture CopyScreen()
{
STexture texture = new STexture(-1);
return texture;
}
public void CopyScreen(ref STexture Texture)
{
return;
}
public void MakeScreenShot()
{
string file = "Screenshot_";
string path = Path.Combine(Environment.CurrentDirectory, CSettings.sFolderScreenshots);
int i = 0;
while (File.Exists(Path.Combine(path, file + i.ToString("00000") + ".bmp")))
i++;
using (Surface surface = _Device.GetBackBuffer(0, 0))
{
Bitmap screen = new Bitmap(Surface.ToStream(surface, ImageFileFormat.Bmp));
screen.Save(Path.Combine(path, file + i.ToString("00000") + ".bmp"), ImageFormat.Bmp);
screen.Dispose();
}
Cursor.Hide();
_Mouse.Visible = true;
}
public void DrawLine(int a, int r, int g, int b, int w, int x1, int y1, int x2, int y2)
{
SColorF color = new SColorF(a / 255, g / 255, b / 255, a / 255);
DrawTexture(blankTexture, new SRectF(x1, y1, x2, y2, 1), color);
}
public void DrawText(string Text, int x, int y, int h)
{
DrawText(Text, x, y, h, 0f);
}
public void DrawText(string Text, int x, int y, float h, float z)
{
CFonts.DrawText(Text, h, x, y, z, new SColorF(1f, 1f, 1f, 1f));
}
public void DrawColor(SColorF color, SRectF rect)
{
DrawTexture(blankTexture, rect, color);
}
#endregion Basic Draw Methods
#region Textures
public STexture AddTexture(string TexturePath)
{
if (System.IO.File.Exists(TexturePath))
{
Bitmap bmp;
try
{
bmp = new Bitmap(TexturePath);
}
catch (Exception)
{
CLog.LogError("Error loading Texture: " + TexturePath);
return new STexture(-1);
}
return AddTexture(bmp, TexturePath);
}
CLog.LogError("Can't find File: " + TexturePath);
return new STexture(-1);
}
private static float NextPowerOfTwo(float n)
{
if (n < 0) throw new ArgumentOutOfRangeException("n", "Must be positive.");
return (float)System.Math.Pow(2, System.Math.Ceiling(System.Math.Log((double)n, 2)));
}
public STexture AddTexture(Bitmap bmp, string TexturePath)
{
STexture texture = new STexture(-1);
if (bmp.Height == 0 || bmp.Width == 0)
return texture;
int MaxSize;
switch (CConfig.TextureQuality)
{
case ETextureQuality.TR_CONFIG_TEXTURE_LOWEST:
MaxSize = 128;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_LOW:
MaxSize = 256;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_MEDIUM:
MaxSize = 512;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_HIGH:
MaxSize = 1024;
break;
case ETextureQuality.TR_CONFIG_TEXTURE_HIGHEST:
MaxSize = 2048;
break;
default:
MaxSize = 512;
break;
}
int w = bmp.Width;
int h = bmp.Height;
if (h >= w && w > MaxSize)
{
h = (int)Math.Round((float)MaxSize / bmp.Width * bmp.Height);
w = MaxSize;
}
if (w >= h && h > MaxSize)
{
w = (int)Math.Round((float)MaxSize / bmp.Height * bmp.Width);
h = MaxSize;
}
texture.width = w;
texture.height = h;
texture.w2 = (float)NextPowerOfTwo(w);
texture.h2 = (float)NextPowerOfTwo(h);
Bitmap bmp2 = new Bitmap((int)texture.w2, (int)texture.h2);
Graphics g = Graphics.FromImage(bmp2);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.DrawImage(bmp, new Rectangle(0, 0, bmp2.Width, bmp2.Height));
g.Dispose();
texture.width_ratio = 1f;
texture.height_ratio = 1f;
BitmapData bmp_data = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
byte[] Data = new byte[4 * bmp2.Width * bmp2.Height];
Marshal.Copy(bmp_data.Scan0, Data, 0, Data.Length);
bmp2.UnlockBits(bmp_data);
Texture t = new Texture(_Device, (int)texture.w2, (int)texture.h2, 0, Usage.AutoGenerateMipMap, Format.A8R8G8B8, Pool.Managed);
DataRectangle rect = t.LockRectangle(0, LockFlags.None);
for (int i = 0; i < Data.Length; )
{
rect.Data.Write(Data, i, 4 * bmp2.Width);
i += 4 * bmp2.Width;
rect.Data.Position = rect.Data.Position - 4 * bmp2.Width;
rect.Data.Position += rect.Pitch;
}
t.UnlockRectangle(0);
_D3DTextures.Add(t);
bmp2.Dispose();
bmp_data = null;
// Add to Texture List
texture.index = _D3DTextures.Count - 1;
texture.color = new SColorF(1f, 1f, 1f, 1f);
texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
texture.TexturePath = String.Empty;
_Textures.Add(texture);
return texture;
}
public STexture AddTexture(Bitmap bmp)
{
return AddTexture(bmp, String.Empty);
}
public STexture AddTexture(int W, int H, IntPtr Data)
{
byte[] PointerData = new Byte[4 * W * H];
Marshal.Copy(Data, PointerData, 0, PointerData.Length);
return AddTexture(W, H , ref PointerData);
}
public STexture AddTexture(int W, int H, ref byte[] Data)
{
STexture texture = new STexture(-1);
texture.width = W;
texture.height = H;
texture.w2 = NextPowerOfTwo(texture.width);
texture.h2 = NextPowerOfTwo(texture.height);
texture.width_ratio = texture.width / texture.w2;
texture.height_ratio = texture.height / texture.h2;
Texture t = new Texture(_Device, (int)texture.w2, (int)texture.h2, 0, Usage.AutoGenerateMipMap, Format.A8R8G8B8, Pool.Managed);
DataRectangle rect = t.LockRectangle(0, LockFlags.None);
for (int i = 0; i < Data.Length; )
{
rect.Data.Write(Data, i, 4 * W);
i += 4 * W;
rect.Data.Position = rect.Data.Position - 4 * W;
rect.Data.Position += rect.Pitch;
}
t.UnlockRectangle(0);
_D3DTextures.Add(t);
texture.index = _D3DTextures.Count - 1;
texture.color = new SColorF(1f, 1f, 1f, 1f);
texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
texture.TexturePath = String.Empty;
_Textures.Add(texture);
return texture;
}
public bool UpdateTexture(ref STexture Texture, IntPtr Data)
{
byte[] PointerData = new Byte[4 * (int)Texture.width * (int)Texture.height];
Marshal.Copy(Data, PointerData, 0, PointerData.Length);
return UpdateTexture(ref Texture, ref PointerData);
}
public bool UpdateTexture(ref STexture Texture, ref byte[] Data)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
{
DataRectangle rect = _D3DTextures[Texture.index].LockRectangle(0, LockFlags.None);
for (int i = 0; i < Data.Length; )
{
rect.Data.Write(Data, i, 4 * (int)Texture.width);
i += 4 * (int)Texture.width;
rect.Data.Position = rect.Data.Position - 4 * (int)Texture.width;
rect.Data.Position += rect.Pitch;
}
_D3DTextures[Texture.index].UnlockRectangle(0);
Texture.height_ratio = Texture.height / NextPowerOfTwo(Texture.height);
Texture.width_ratio = Texture.width / NextPowerOfTwo(Texture.width);
}
return true;
}
private bool _TextureExists(STexture Texture)
{
if ((Texture.index > 0) && (_Textures.Count > 0))
{
for (int i = 0; i < _Textures.Count; i++)
{
if (_Textures[i].index == Texture.index)
{
return true;
}
}
}
return false;
}
public void RemoveTexture(ref STexture Texture)
{
if ((Texture.index >= 0) && (_Textures.Count > 0))
{
for (int i = 0; i < _Textures.Count; i++)
{
if (_Textures[i].index == Texture.index)
{
_D3DTextures[Texture.index].Dispose();
_Textures.RemoveAt(i);
Texture.index = -1;
GC.Collect();
break;
}
}
}
}
public void DrawTexture(STexture Texture)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
DrawTexture(Texture, Texture.rect, Texture.color);
}
public void DrawTexture(STexture Texture, SRectF rect)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
DrawTexture(Texture, rect, Texture.color, false);
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
DrawTexture(Texture, rect, color, false);
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
DrawTexture(Texture, rect, color, bounds, false);
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, bool mirrored)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
DrawTexture(Texture, rect, color, new SRectF(0, 0, CSettings.iRenderW, CSettings.iRenderH, rect.Z), mirrored);
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
{
float x1 = (bounds.X - rect.X) / rect.W * Texture.width_ratio;
float x2 = (bounds.X + bounds.W - rect.X) / rect.W * Texture.width_ratio;
float y1 = (bounds.Y - rect.Y) / rect.H * Texture.height_ratio;
float y2 = (bounds.Y + bounds.H - rect.Y) / rect.H * Texture.height_ratio;
if (x1 < 0)
x1 = 0f;
if (x2 > Texture.width_ratio)
x2 = Texture.width_ratio;
if (y1 < 0)
y1 = 0f;
if (y2 > Texture.height_ratio)
y2 = Texture.height_ratio;
float rx1 = rect.X;
float rx2 = rect.X + rect.W;
float ry1 = rect.Y;
float ry2 = rect.Y + rect.H;
if (rx1 < bounds.X)
rx1 = bounds.X;
if (rx2 > bounds.X + bounds.W)
rx2 = bounds.X + bounds.W;
if (ry1 < bounds.Y)
ry1 = bounds.Y;
if (ry2 > bounds.Y + bounds.H)
ry2 = bounds.Y + bounds.H;
rx1 -= 0.5f; // Align pixels
ry1 -= 0.5f;
rx2 -= 0.5f;
ry2 -= 0.5f;
if (color.R >= 1f)
color.R = 1f;
if (color.B >= 1f)
color.B = 1f;
if (color.G >= 1f)
color.G = 1f;
if (rect.Rotation != 0)
{
rect.Rotation = rect.Rotation * (float)Math.PI / 180;
float centerX = (rx1 + rx2) / 2f;
float centerY = -(ry1 + ry2) / 2f;
Matrix originTranslation = _Device.GetTransform(TransformState.World);
Matrix translationA = Matrix.Translation(-centerX, -centerY, 0);
Matrix rotation = Matrix.RotationZ(-rect.Rotation);
Matrix translationB = Matrix.Translation(centerX, centerY, 0);
Matrix result = translationA * rotation * translationB * originTranslation;
_Device.SetTransform(TransformState.World, result);
}
Color c = Color.FromArgb((int)(color.A * 255 * CGraphics.GlobalAlpha), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));
DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.Discard);
if (!mirrored)
{
stream.WriteRange(new[] {
new TexturedColoredVertex(new Vector3(rx1, -ry1, rect.Z + CGraphics.ZOffset), new Vector2(x1, y1), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx1, -ry2, rect.Z + CGraphics.ZOffset), new Vector2(x1, y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, -ry2, rect.Z + CGraphics.ZOffset), new Vector2(x2, y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, -ry1, rect.Z + CGraphics.ZOffset), new Vector2(x2, y1), c.ToArgb()),
});
}
else
{
stream.WriteRange(new[] {
new TexturedColoredVertex(new Vector3(rx1, -ry1, rect.Z + CGraphics.ZOffset), new Vector2(x1, -y1), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx1, -ry2, rect.Z + CGraphics.ZOffset), new Vector2(x1, -y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, -ry2, rect.Z + CGraphics.ZOffset), new Vector2(x2, -y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, -ry1, rect.Z + CGraphics.ZOffset), new Vector2(x2, -y1), c.ToArgb()),
});
}
_VertexBuffer.Unlock();
stream.Dispose();
_Device.SetTexture(0, _D3DTextures[Texture.index]);
_Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);
if (rect.Rotation != 0)
{
Matrix originTranslation = Matrix.Translation(new Vector3(-CSettings.iRenderW / 2, CSettings.iRenderH / 2, 0));
_Device.SetTransform(TransformState.World, originTranslation);
}
}
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, float begin, float end)
{
float x1 = 0f + begin * Texture.width_ratio;
float x2 = Texture.width_ratio * end;
float y1 = 0f;
float y2 = Texture.height_ratio;
float rx1 = rect.X + begin* rect.W;
float rx2 = rect.X + end * rect.W;
float ry1 = rect.Y;
float ry2 = rect.Y + rect.H;
rx1 -= 0.5f; // Align pixels
ry1 -= 0.5f;
rx2 -= 0.5f;
ry2 -= 0.5f;
Color c = Color.FromArgb((int)(color.A * 255 * CGraphics.GlobalAlpha), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));
DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.Discard);
stream.WriteRange(new[] {
new TexturedColoredVertex(new Vector3(rx1, ry1*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x1, y1), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx1, ry2*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x1, y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, ry2*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x2, y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, ry1*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x2, y1), c.ToArgb()),
});
_VertexBuffer.Unlock();
stream.Dispose();
_Device.SetTexture(0, _D3DTextures[Texture.index]);
_Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);
}
public void DrawTextureReflection(STexture Texture, SRectF rect, SColorF color, SRectF bounds, float space, float height)
{
if (rect.W == 0f || rect.H == 0f || bounds.H == 0f || bounds.W == 0f || color.A == 0f || height <= 0f)
return;
if (bounds.X > rect.X + rect.W || bounds.X + bounds.W < rect.X)
return;
if (bounds.Y > rect.Y + rect.H || bounds.Y + bounds.H < rect.Y)
return;
if (height > bounds.H)
height = bounds.H;
if (_TextureExists(Texture))
{
float x1 = (bounds.X - rect.X) / rect.W * Texture.width_ratio;
float x2 = (bounds.X + bounds.W - rect.X) / rect.W * Texture.width_ratio;
float y1 = (bounds.Y - rect.Y + rect.H - height) / rect.H * Texture.height_ratio;
float y2 = (bounds.Y + bounds.H - rect.Y) / rect.H * Texture.height_ratio;
if (x1 < 0)
x1 = 0f;
if (x2 > Texture.width_ratio)
x2 = Texture.width_ratio;
if (y1 < 0)
y1 = 0f;
if (y2 > Texture.height_ratio)
y2 = Texture.height_ratio;
float rx1 = rect.X;
float rx2 = rect.X + rect.W;
float ry1 = rect.Y + rect.H + space;
float ry2 = rect.Y + rect.H + space + height;
if (rx1 < bounds.X)
rx1 = bounds.X;
if (rx2 > bounds.X + bounds.W)
rx2 = bounds.X + bounds.W;
if (ry1 < bounds.Y + space)
ry1 = bounds.Y + space;
if (ry2 > bounds.Y + bounds.H + space + height)
ry2 = bounds.Y + bounds.H + space + height;
rx1 -= 0.5f; // Align pixels
ry1 -= 0.5f;
rx2 -= 0.5f;
ry2 -= 0.5f;
DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.Discard);
Color c = Color.FromArgb((int)(color.A * 255 * CGraphics.GlobalAlpha), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));
Color t = Color.FromArgb(0, (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));
stream.WriteRange(new[] {
new TexturedColoredVertex(new Vector3(rx2, -ry1, rect.Z + CGraphics.ZOffset), new Vector2(x2, y2), c.ToArgb()),
new TexturedColoredVertex(new Vector3(rx2, -ry2, rect.Z + CGraphics.ZOffset), new Vector2(x2, y1), t.ToArgb()),
new TexturedColoredVertex(new Vector3(rx1, -ry2, rect.Z + CGraphics.ZOffset), new Vector2(x1, y1), t.ToArgb()),
new TexturedColoredVertex(new Vector3(rx1, -ry1, rect.Z + CGraphics.ZOffset), new Vector2(x1, y2), c.ToArgb()),
});
_VertexBuffer.Unlock();
stream.Dispose();
_Device.SetTexture(0, _D3DTextures[Texture.index]);
_Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);
}
}
public int TextureCount()
{
return _Textures.Count;
}
#endregion Textures
#endregion implementation
#region TexturedColoredVertex
public struct TexturedColoredVertex
{
private static VertexDeclaration sDeclaration;
public static VertexElement[] Elements =
{
new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
new VertexElement(0, sizeof(float) *3, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
new VertexElement(0, sizeof(float) * 3 + sizeof(float)*2, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
VertexElement.VertexDeclarationEnd
};
public Vector3 Position;
public Vector2 Texture;
public int Color;
public TexturedColoredVertex(Vector3 position, Vector2 texture, int color)
{
this.Position = position;
this.Texture = texture;
this.Color = color;
}
public static VertexDeclaration GetDeclaration(Device device)
{
if (sDeclaration == null || sDeclaration.Disposed)
{
sDeclaration = new VertexDeclaration(device, Elements);
}
return sDeclaration;
}
}
#endregion TexturedColoredVertex
}
}
+518
View File
@@ -0,0 +1,518 @@
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Vocaluxe.Base;
using Vocaluxe.Menu;
namespace Vocaluxe.Lib.Draw
{
class CDrawWinForm : Form, IDraw
{
private bool _Run;
private Bitmap _backbuffer;
private Graphics _g;
private bool _fullscreen = false;
private CKeys _Keys;
private CMouse _Mouse;
private FormBorderStyle _brdStyle;
private bool _topMost;
private Rectangle _bounds;
private List<STexture> _Textures;
private List<Bitmap> _Bitmaps;
private Color ClearColor = Color.DarkBlue;
public CDrawWinForm()
{
this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon));
_Textures = new List<STexture>();
_Bitmaps = new List<Bitmap>();
_Keys = new CKeys();
_Mouse = new CMouse();
this.ClientSize = new Size(1280, 720);
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Opaque, true);
// Create the backbuffer
_backbuffer = new Bitmap(CSettings.iRenderW, CSettings.iRenderH);
_g = Graphics.FromImage(_backbuffer);
_g.Clear(Color.DarkBlue);
this.Paint += new PaintEventHandler(this.OnPaintEvent);
this.Closing += new CancelEventHandler(this.OnClosingEvent);
this.KeyDown += new KeyEventHandler(this.OnKeyDownEvent);
this.KeyPress += new KeyPressEventHandler(this.OnKeyPressEvent);
this.KeyUp += new KeyEventHandler(this.OnKeyUpEvent);
this.Resize += new EventHandler(this.OnResizeEvent);
this.MouseMove += new MouseEventHandler(this.OnMouseMove);
this.MouseDown += new MouseEventHandler(this.OnMouseDown);
this.MouseUp += new MouseEventHandler(this.OnMouseUp);
FlipBuffer();
Cursor.Show();
}
private void FlipBuffer()
{
DrawBuffer();
_g.Clear(ClearColor);
}
private void DrawBuffer()
{
Graphics gFrontBuffer = Graphics.FromHwnd(this.Handle);
int h = this.ClientSize.Height;
int w = this.ClientSize.Width;
int y = 0;
int x = 0;
if ((float)this.ClientSize.Width / (float)this.ClientSize.Height > CSettings.GetRenderAspect())
{
w = (int)Math.Round((float)this.ClientSize.Height * CSettings.GetRenderAspect());
x = (this.ClientSize.Width - w) / 2;
}
else
{
h = (int)Math.Round((float)this.ClientSize.Width / CSettings.GetRenderAspect());
y = (this.ClientSize.Height - h) / 2;
}
gFrontBuffer.DrawImage(_backbuffer, new Rectangle(x, y, w, h), new Rectangle(0, 0, _backbuffer.Width, _backbuffer.Height), GraphicsUnit.Pixel);
}
private void OnPaintEvent(object sender, PaintEventArgs e)
{
}
#region FullScreenStuff
private void ToggleFullScreen()
{
if (!_fullscreen)
Maximize(this);
else
Restore(this);
}
private void Maximize(Form targetForm)
{
if (!_fullscreen)
{
Save(targetForm);
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.Bounds = Screen.PrimaryScreen.Bounds;
targetForm.TopMost = true;
_fullscreen = true;
CConfig.FullScreen = EOffOn.TR_CONFIG_ON;
CConfig.SaveConfig();
}
}
private void Save(Form targetForm)
{
_brdStyle = targetForm.FormBorderStyle;
_topMost = targetForm.TopMost;
_bounds = targetForm.Bounds;
}
private void Restore(Form targetForm)
{
targetForm.FormBorderStyle = _brdStyle;
targetForm.TopMost = _topMost;
targetForm.Bounds = _bounds;
_fullscreen = false;
CConfig.FullScreen = EOffOn.TR_CONFIG_OFF;
CConfig.SaveConfig();
}
#endregion FullScreenStuff
private void OnResizeEvent(object sender, EventArgs e)
{
Graphics gFrontBuffer = Graphics.FromHwnd(this.Handle);
gFrontBuffer.Clear(Color.Black);
}
private void OnClosingEvent(object sender, CancelEventArgs e)
{
_Run = false;
}
private void OnKeyDownEvent(object sender, System.Windows.Forms.KeyEventArgs e)
{
_Keys.KeyDown(e);
}
private void OnKeyPressEvent(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
_Keys.KeyPress(e);
}
private void OnKeyUpEvent(object sender, System.Windows.Forms.KeyEventArgs e)
{
_Keys.KeyUp(e);
}
#region mouse event handlers
private void OnMouseMove(object sender, MouseEventArgs e)
{
_Mouse.MouseMove(e);
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
_Mouse.MouseDown(e);
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
_Mouse.MouseUp(e);
}
#endregion
public bool Init()
{
this.Text = CSettings.GetFullVersionText();
return true;
}
public void MainLoop()
{
_Run = true;
int delay = 0;
this.Show();
if (CConfig.FullScreen == EOffOn.TR_CONFIG_ON)
{
CSettings.bFullScreen = true;
Maximize(this);
}
while (_Run)
{
Application.DoEvents();
if (_Run)
{
_Run = _Run && CGraphics.Draw();
_Run = CGraphics.UpdateGameLogic(_Keys, _Mouse);
FlipBuffer();
if ((CSettings.bFullScreen && !_fullscreen) || (!CSettings.bFullScreen && _fullscreen))
ToggleFullScreen();
if (CTime.IsRunning())
delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds());
if (delay >= 1)
System.Threading.Thread.Sleep(delay);
CTime.CalculateFPS();
CTime.Restart();
}
else
this.Close();
}
}
public bool Unload()
{
this.Dispose();
return true;
}
public int GetScreenWidth()
{
return this.ClientSize.Width;
}
public int GetScreenHeight()
{
return this.ClientSize.Height;
}
public RectangleF GetTextBounds(CText text)
{
return GetTextBounds(text, text.Height);
}
public RectangleF GetTextBounds(CText text, float Height)
{
CFonts.Height = Height;
CFonts.SetFont(text.Fon);
CFonts.Style = text.Style;
return new RectangleF(text.X, text.Y, CFonts.GetTextWidth(CLanguage.Translate(text.Text)), CFonts.GetTextHeight(text.Text));
}
public void ClearScreen()
{
_g.Clear(ClearColor);
}
public STexture CopyScreen()
{
STexture texture = new STexture(0);
Bitmap bmp = new Bitmap(_backbuffer);
_Bitmaps.Add(bmp);
texture.index = _Bitmaps.Count - 1;
texture.width = bmp.Width;
texture.height = bmp.Height;
// Add to Texture List
texture.color = new SColorF(1f, 1f, 1f, 1f);
texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
_Textures.Add(texture);
return texture;
}
public void CopyScreen(ref STexture Texture)
{
if ((Texture.index == 0) || (Texture.width != GetScreenWidth()) || (Texture.height != GetScreenHeight()))
{
RemoveTexture(ref Texture);
Texture = CopyScreen();
}
else
{
_Bitmaps[Texture.index] = new Bitmap(_backbuffer);
}
}
public void MakeScreenShot()
{
string file = "Screenshot_";
string path = Path.Combine(Environment.CurrentDirectory, CSettings.sFolderScreenshots);
int i = 0;
while (File.Exists(Path.Combine(path, file + i.ToString("00000") + ".png")))
i++;
_backbuffer.Save(Path.Combine(path, file + i.ToString("00000") + ".png"), ImageFormat.Png);
}
public void DrawLine(int a, int r, int g, int b, int w, int x1, int y1, int x2, int y2)
{
_g.DrawLine(new Pen(Color.FromArgb(a, r, g, b), w), new Point(x1, y1), new Point(x2, y2));
}
// Draw Basic Text
public void DrawText(string Text, int x, int y, int h)
{
DrawText(Text, x, y, h, 0f);
}
// Draw Basic Text
public void DrawText(string Text, int x, int y, float h, float z)
{
CFonts.DrawText(Text, h, x, y, z, new SColorF(1, 1, 1, 1));
}
public void DrawColor(SColorF color, SRectF rect)
{
}
public STexture AddTexture(Bitmap bmp)
{
Bitmap bmp2 = new Bitmap(bmp);
_Bitmaps.Add(bmp2);
STexture texture = new STexture();
texture.index = _Bitmaps.Count - 1;
texture.width = bmp.Width;
texture.height = bmp.Height;
// Add to Texture List
texture.color = new SColorF(1f, 1f, 1f, 1f);
texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
texture.TexturePath = String.Empty;
_Textures.Add(texture);
return texture;
}
public STexture AddTexture(string TexturePath)
{
STexture texture = new STexture();
if (System.IO.File.Exists(TexturePath))
{
bool found = false;
foreach(STexture tex in _Textures)
{
if (tex.TexturePath == TexturePath)
{
texture = tex;
found = true;
break;
}
}
if (!found)
{
Bitmap bmp = new Bitmap(TexturePath);
return AddTexture(bmp);
}
}
return texture;
}
public void RemoveTexture(ref STexture Texture)
{
if ((Texture.index >= 0) && (_Textures.Count > 0))
{
for (int i = 0; i < _Textures.Count; i++)
{
if (_Textures[i].index == Texture.index)
{
_Bitmaps[Texture.index].Dispose();
_Textures.RemoveAt(i);
Texture.index = -1;
break;
}
}
}
}
public STexture AddTexture(int W, int H, IntPtr Data)
{
return new STexture(-1);
}
public STexture AddTexture(int W, int H, ref byte[] Data)
{
Bitmap bmp = new Bitmap(W, H);
BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Marshal.Copy(Data, 0, bmp_data.Scan0, Data.Length);
bmp.UnlockBits(bmp_data);
return AddTexture(bmp);
}
public bool UpdateTexture(ref STexture Texture, IntPtr Data)
{
return true;
}
public bool UpdateTexture(ref STexture Texture, ref byte[] Data)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index))
{
BitmapData bmp_data = _Bitmaps[Texture.index].LockBits(new Rectangle(0, 0, _Bitmaps[Texture.index].Width, _Bitmaps[Texture.index].Height),
ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Marshal.Copy(Data, 0, bmp_data.Scan0, Data.Length);
_Bitmaps[Texture.index].UnlockBits(bmp_data);
}
return true;
}
public void DrawTexture(STexture Texture)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index))
{
DrawTexture(Texture, Texture.rect, Texture.color);
}
}
public void DrawTexture(STexture Texture, SRectF rect)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index))
{
DrawTexture(Texture, rect, Texture.color);
}
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index))
{
DrawTexture(Texture, rect, color, rect, false);
}
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index))
{
DrawTexture(Texture, rect, color, bounds, false);
}
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, bool mirrored)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index))
{
DrawTexture(Texture, rect, color, rect, mirrored);
}
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored)
{
if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index))
{
Bitmap ColoredBitmap = ColorizeBitmap(_Bitmaps[Texture.index], color);
_g.DrawImage(ColoredBitmap, new RectangleF(rect.X, rect.Y, rect.W, rect.H));
ColoredBitmap.Dispose();
}
}
public void DrawTexture(STexture Texture, SRectF rect, SColorF color, float begin, float end)
{
}
public void DrawTextureReflection(STexture Texture, SRectF rect, SColorF color, SRectF bounds, float space, float height)
{
}
public int TextureCount()
{
return _Textures.Count;
}
public static Bitmap ColorizeBitmap(Bitmap original, SColorF color)
{
Bitmap newBitmap = new Bitmap(original.Width, original.Height);
Graphics g = Graphics.FromImage(newBitmap);
ColorMatrix cm = new ColorMatrix();
cm.Matrix33 = color.A;
cm.Matrix00 = color.R;
cm.Matrix11 = color.G;
cm.Matrix22 = color.B;
cm.Matrix44 = 1;
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm);
g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height, GraphicsUnit.Pixel, ia);
ia.Dispose();
g.Dispose();
return newBitmap;
}
}
}
File diff suppressed because it is too large. Load diff
+156
View File
@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using Vocaluxe.Base;
using Vocaluxe.Menu;
namespace Vocaluxe.Lib.Draw
{
#region Structs
public struct SColorF
{
public float R;
public float G;
public float B;
public float A;
public SColorF(float r, float g, float b, float a)
{
R = r;
G = g;
B = b;
A = a;
}
public SColorF(SColorF Color)
{
R = Color.R;
G = Color.G;
B = Color.B;
A = Color.A;
}
}
public struct SRectF
{
public float X;
public float Y;
public float W;
public float H;
public float Z;
public float Rotation; //0..360°
public SRectF(float x, float y, float w, float h, float z)
{
X = x;
Y = y;
W = w;
H = h;
Z = z;
Rotation = 0f;
}
public SRectF(SRectF rect)
{
X = rect.X;
Y = rect.Y;
W = rect.W;
H = rect.H;
Z = rect.Z;
Rotation = 0f;
}
}
public struct STexture
{
public int index;
public int PBO;
public string TexturePath;
public float width;
public float height;
public SRectF rect;
public float w2; //power of 2 width
public float h2; //power of 2 height
public float width_ratio;
public float height_ratio;
public SColorF color;
public STexture(int Index)
{
index = Index;
PBO = 0;
TexturePath = String.Empty;
width = 0f;
height = 0f;
rect = new SRectF(0f, 0f, 1f, 1f, 0f);
w2 = 2f;
h2 = 2f;
width_ratio = 0.5f;
height_ratio = 0.5f;
color = new SColorF(1f, 1f, 1f, 1f);
}
}
#endregion Structs
enum EAspect
{
Crop,
LetterBox,
Stretch
}
interface IDraw
{
bool Init();
void MainLoop();
bool Unload();
int GetScreenWidth();
int GetScreenHeight();
RectangleF GetTextBounds(CText text);
RectangleF GetTextBounds(CText text, float Height);
// Basic Draw Methods
void DrawLine(int a, int r, int g, int b, int w, int x1, int y1, int x2, int y2);
void DrawColor(SColorF color, SRectF rect);
void ClearScreen();
STexture CopyScreen();
void CopyScreen(ref STexture Texture);
void MakeScreenShot();
// Draw Basic Text (must be deleted later)
void DrawText(string Text, int x, int y, int h);
STexture AddTexture(string TexturePath);
STexture AddTexture(Bitmap Bitmap);
STexture AddTexture(int W, int H, IntPtr Data);
STexture AddTexture(int W, int H, ref byte[] Data);
bool UpdateTexture(ref STexture Texture, ref byte[] Data);
bool UpdateTexture(ref STexture Texture, IntPtr Data);
void RemoveTexture(ref STexture Texture);
void DrawTexture(STexture Texture);
void DrawTexture(STexture Texture, SRectF rect);
void DrawTexture(STexture Texture, SRectF rect, SColorF color);
void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds);
void DrawTexture(STexture Texture, SRectF rect, SColorF color, bool mirrored);
void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored);
void DrawTexture(STexture Texture, SRectF rect, SColorF color, float begin, float end);
void DrawTextureReflection(STexture Texture, SRectF rect, SColorF color, SRectF bounds, float space, float height);
int TextureCount();
}
}
+653
View File
@@ -0,0 +1,653 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Base;
namespace Vocaluxe.Lib.Song
{
class CNotes
{
private List<CLines> _Lines = new List<CLines>();
public CLines[] Lines
{
get { return _Lines.ToArray(); }
}
public CLines GetLines(int Index)
{
while (Index >= _Lines.Count)
{
_Lines.Add(new CLines());
}
return _Lines[Index];
}
public int GetPoints(int Index)
{
if (Index >= _Lines.Count)
return 0;
return _Lines[Index].Points;
}
public void AddLines(CLines Lines)
{
_Lines.Add(Lines);
}
public bool ReplaceLinesAt(int Index, CLines Lines)
{
if (Index >= _Lines.Count)
return false;
CLines lines = new CLines();
lines = Lines;
_Lines[Index] = lines;
return true;
}
public void Reset()
{
_Lines.Clear();
}
}
public enum ENoteType
{
Normal,
Golden,
Freestyle
}
public class CNote
{
private int _StartBeat;
private int _Duration;
private int _Tone;
private ENoteType _NoteType;
private string _Text;
private bool _Hit; // for drawing player notes
private bool _Perfect; // for drawing perfect note effect
#region Contructors
public CNote()
{
StartBeat = 0;
Duration = 1;
Tone = 0;
NoteType = ENoteType.Normal;
Text = String.Empty;
_Hit = false;
_Perfect = false;
}
public CNote(int StartBeat, int Duration, int Tone, string Text)
: this()
{
this.StartBeat = StartBeat;
this.Duration = Duration;
this.Tone = Tone;
this.NoteType = ENoteType.Normal;
this.Text = Text;
}
public CNote(int StartBeat, int Duration, int Tone, string Text, bool Hit)
: this()
{
this.StartBeat = StartBeat;
this.Duration = Duration;
this.Tone = Tone;
this.NoteType = ENoteType.Normal;
this.Text = Text;
this.Hit = Hit;
}
public CNote(int StartBeat, int Duration, int Tone, string Text, ENoteType NoteType)
: this(StartBeat, Duration, Tone, Text)
{
this.NoteType = NoteType;
}
public CNote(int StartBeat, int Duration, int Tone, string Text, bool Hit, ENoteType NoteType)
: this(StartBeat, Duration, Tone, Text)
{
this.NoteType = NoteType;
this.Hit = Hit;
}
#endregion Constructors
#region Properties
public bool Hit
{
get { return _Hit; }
set { _Hit = value; }
}
public bool Perfect
{
get { return _Perfect; }
set { _Perfect = value; }
}
public int StartBeat
{
get { return _StartBeat; }
set { _StartBeat = value; }
}
public int EndBeat
{
get
{
return _StartBeat + _Duration - 1;
}
}
public int Duration
{
get { return _Duration; }
set
{
if (value > 0)
_Duration = value;
}
}
public int Tone
{
get { return _Tone; }
set
{
if ((value >= CSettings.ToneMin) && (value <= CSettings.ToneMax))
_Tone = value;
}
}
public ENoteType NoteType
{
get { return _NoteType; }
set { _NoteType = value; }
}
public string Text
{
get { return _Text; }
set { _Text = value; }
}
public int Points
{
get
{
switch (_NoteType)
{
case ENoteType.Normal:
return _Duration;
case ENoteType.Golden:
return _Duration * 2;
case ENoteType.Freestyle:
return 0;
default:
return 0;
}
}
}
public int PointsForBeat
{
get
{
switch (_NoteType)
{
case ENoteType.Normal:
return 1;
case ENoteType.Golden:
return 2;
case ENoteType.Freestyle:
return 0;
default:
return 0;
}
}
}
#endregion Properties
#region Methods
public bool IsPerfect(CNote CompareNote)
{
bool Result = true;
if (!Hit)
Result = false;
if (StartBeat != CompareNote.StartBeat)
Result = false;
if (EndBeat != CompareNote.EndBeat)
Result = false;
if (Tone != CompareNote.Tone)
Result = false;
Perfect = Result;
return Result;
}
#endregion Methods
}
public class CLine
{
private int _StartBeat;
private int _EndBeat;
private bool _PerfectLine; // for drawing perfect line effect
private List<CNote> _Notes;
#region Constructors
public CLine()
{
_Notes = new List<CNote>();
StartBeat = int.MinValue;
EndBeat = int.MaxValue;
_PerfectLine = false;
}
#endregion Constructors
#region Properties
public int StartBeat
{
get { return _StartBeat; }
set
{
int min = int.MaxValue;
foreach (CNote note in _Notes)
{
if (note.StartBeat < min)
min = note.StartBeat;
}
if (value <= min)
_StartBeat = value;
}
}
public int EndBeat
{
get { return _EndBeat; }
set
{
int max = int.MinValue;
foreach (CNote note in _Notes)
{
if (note.EndBeat > max)
max = note.EndBeat;
}
if (value >= max)
_EndBeat = value;
}
}
public bool PerfectLine
{
get { return _PerfectLine; }
set { _PerfectLine = value; }
}
public int FirstBeat
{
get
{
int Result = int.MaxValue;
foreach (CNote note in _Notes)
{
if (note.StartBeat < Result)
Result = note.StartBeat;
}
return Result;
}
}
public int LastBeat
{
get
{
int Result = int.MinValue;
foreach (CNote note in _Notes)
{
if (note.EndBeat > Result)
Result = note.EndBeat;
}
return Result;
}
}
public string Lyrics
{
get
{
string lyrics = String.Empty;
foreach (CNote note in _Notes)
{
lyrics += note.Text;
}
return lyrics;
}
}
public int NoteCount
{
get { return _Notes.Count; }
}
public int Points
{
get
{
int points = 0;
foreach (CNote note in _Notes)
{
points += note.Points;
}
return points;
}
}
public CNote[] Notes
{
get
{
return _Notes.ToArray();
}
}
public CNote FirstNote
{
get
{
if (_Notes.Count > 0)
return _Notes[0];
else
return null;
}
}
public CNote LastNote
{
get
{
if (_Notes.Count > 0)
return _Notes[_Notes.Count - 1];
else
return null;
}
}
public int BaseLine
{
get
{
int Min = int.MaxValue;
foreach (CNote note in _Notes)
{
if (note.Tone < Min)
Min = note.Tone;
}
int Max = int.MinValue;
foreach (CNote note in _Notes)
{
if (note.Tone > Max)
Max = note.Tone;
}
return Min - (Max-Min)/4;
}
}
#endregion Properties
#region Methods
public bool IsPerfect(CLine CompareLine)
{
if (_Notes.Count == 0)
return false;
if (_Notes.Count != CompareLine.NoteCount)
return false;
if (CompareLine.Points == 0)
return false;
_PerfectLine = (this.Points == CompareLine.Points);
return _PerfectLine;
}
public void AddNote(CNote Note)
{
_Notes.Add(Note);
}
public bool InsertNote(CNote Note, int Index)
{
if (_Notes.Count >= Index)
{
_Notes.Insert(Index, Note);
return true;
}
return false;
}
public bool DeleteNote(int Index)
{
if (_Notes.Count > Index)
{
_Notes.RemoveAt(Index);
return true;
}
return false;
}
public bool ReplaceNote(int Index, CNote Note)
{
if (_Notes.Count > Index)
{
_Notes.RemoveAt(Index);
_Notes.Insert(Index, Note);
return true;
}
return false;
}
public bool IncLastNoteLength()
{
if (_Notes.Count > 0)
{
_Notes[_Notes.Count - 1].Duration++;
}
return false;
}
public void DeleteAllNotes()
{
_Notes.Clear();
}
#endregion Methods
}
public class CLines
{
private List<CLine> _Lines;
public CLines()
{
_Lines = new List<CLine>();
}
public CLine[] Line
{
get { return _Lines.ToArray(); }
}
public int LineCount
{
get { return _Lines.Count; }
}
/// <summary>
/// Total song length in beats
/// </summary>
public int Length
{
get
{
if (_Lines.Count == 0)
return 0;
int startbeat = int.MaxValue;
for (int i = 0; i < _Lines.Count; i++)
{
if (_Lines[i].FirstBeat < startbeat)
startbeat = _Lines[i].FirstBeat;
}
int endbeat = int.MinValue;
for (int i = 0; i < _Lines.Count; i++)
{
if (_Lines[i].LastBeat < endbeat)
endbeat = _Lines[i].LastBeat;
}
int result = endbeat - startbeat;
if (result > 0)
return result;
return 0;
}
}
public int Points
{
get
{
int points = 0;
foreach (CLine line in _Lines)
{
points += line.Points;
}
return points;
}
}
#region Methods
public void AddLine(CLine Line)
{
_Lines.Add(Line);
UpdateTimings();
}
public bool InsertLine(CLine Line, int Index)
{
if (_Lines.Count >= Index)
{
_Lines.Insert(Index, Line);
UpdateTimings();
return true;
}
return false;
}
public bool DeleteLine(int Index)
{
if (_Lines.Count > Index)
{
_Lines.RemoveAt(Index);
UpdateTimings();
return true;
}
return false;
}
public void DeleteAllLines()
{
_Lines.Clear();
}
public bool AddNote(CNote Note, int LineIndex)
{
if (_Lines.Count > LineIndex)
{
_Lines[LineIndex].AddNote(Note);
UpdateTimings();
return true;
}
return false;
}
public bool InsertNote(CNote Note, int LineIndex, int NoteIndex)
{
if (_Lines.Count > LineIndex)
{
bool res = _Lines[LineIndex].InsertNote(Note, NoteIndex);
UpdateTimings();
return res;
}
return false;
}
public void UpdateTimings()
{
CNote LastNote, FirstNote;
int min, max, s;
if (_Lines.Count > 0)
{
_Lines[0].StartBeat = -10000;
}
for (int i = 1; i < _Lines.Count; i++)
{
LastNote = _Lines[i - 1].LastNote;
FirstNote = _Lines[i].FirstNote;
if ((LastNote != null) && (FirstNote != null))
{
min = LastNote.EndBeat;
max = FirstNote.StartBeat;
s = 0;
switch (max - min)
{
case 0:
s = max;
break;
case 1:
s = max;
break;
case 2:
s = max - 1;
break;
case 3:
s = max - 2;
break;
default:
s = min + 2;
break;
}
_Lines[i].StartBeat = s;
_Lines[i - 1].EndBeat = min;
}
}
LastNote = _Lines[_Lines.Count - 1].LastNote;
if (LastNote != null)
{
_Lines[_Lines.Count - 1].EndBeat = LastNote.EndBeat;
}
}
#endregion Methods
}
}
+527
View File
@@ -0,0 +1,527 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Menu;
namespace Vocaluxe.Lib.Song
{
[Flags]
enum EHeaderFlags
{
Title,
Artist,
MP3,
BPM,
PreviewStart,
MedleyStartBeat,
MedleyEndBeat
}
class CSong
{
private bool _CoverLoaded = false;
private STexture _CoverTextureSmall = new STexture(-1);
private STexture _CoverTextureBig = new STexture(-1);
public Encoding Encoding = Encoding.Default;
public string Folder = String.Empty;
public string FolderName = String.Empty;
public string FileName = String.Empty;
public string MP3FileName = String.Empty;
public string CoverFileName = String.Empty;
public string BackgroundFileName = String.Empty;
public string VideoFileName = String.Empty;
public EAspect VideoAspect = EAspect.Crop;
public bool CoverSmallLoaded
{
get { return _CoverLoaded; }
}
public bool CoverBigLoaded = false;
public bool BackgroundLoaded = false;
public STexture CoverTextureSmall
{
get
{
if (!_CoverLoaded)
{
this.ReadNotes();
if (this.CoverFileName != String.Empty)
{
if (!CDataBase.GetCover(Path.Combine(this.Folder, this.CoverFileName), ref _CoverTextureSmall, CConfig.CoverSize))
_CoverTextureSmall = CCover.NoCover;
}
else
_CoverTextureSmall = CCover.NoCover;
_CoverLoaded = true;
}
return _CoverTextureSmall;
}
set
{
_CoverTextureSmall = value;
_CoverLoaded = true;
}
}
public STexture CoverTextureBig
{
get { return _CoverTextureBig; }
set { _CoverTextureBig = value; }
}
public CBackground Background = new CBackground();
public string Title = String.Empty;
public string Artist = String.Empty;
public float Start = 0f;
public float Finish = 0f;
public float BPM = 1f;
public float Gap = 0f;
public float VideoGap = 0f;
public List<string> Comment = new List<string>();
// Sorting
public int ID;
public bool Visible = true;
public int CatIndex = -1;
public bool Selected = false;
public bool IsDuet
{
get { return Notes.Lines.Length > 1; }
}
public List<string> Edition = new List<string>();
public List<string> Genre = new List<string>();
public string Year = "0000";
public List<string> Language = new List<string>();
// Notes
public CNotes Notes = new CNotes();
public string GetMP3()
{
return Path.Combine(Folder, MP3FileName);
}
public bool ReadTXTSong(string FilePath)
{
if (!File.Exists(FilePath))
return false;
if (!ReadTXTHeader(FilePath))
return false;
return true;
}
public bool ReadTXTHeader(string FilePath)
{
if (!File.Exists(FilePath))
return false;
this.Folder = Path.GetDirectoryName(FilePath);
foreach (string folder in CConfig.SongFolder)
{
if (this.Folder.Contains(folder))
{
if (this.Folder.Length == folder.Length)
this.FolderName = "Songs";
else
{
this.FolderName = this.Folder.Substring(folder.Length + 1, this.Folder.Length - folder.Length - 1);
string str = this.FolderName;
try
{
str = this.FolderName.Substring(0, this.FolderName.IndexOf("\\"));
}
catch (Exception)
{
}
this.FolderName = str;
}
}
}
this.FileName = Path.GetFileName(FilePath);
EHeaderFlags HeaderFlags = new EHeaderFlags();
StreamReader sr;
try
{
sr = new StreamReader(FilePath, Encoding.Default, true);
string line = sr.ReadLine();
if (line.Length == 0)
return false;
int pos = -1;
string Identifier = String.Empty;
string Value = String.Empty;
while ((line.Length == 0) || (line[0].ToString().Equals("#")))
{
pos = line.IndexOf(":");
if (pos > 0)
{
Identifier = line.Substring(1, pos - 1).Trim().ToUpper();
Value = line.Substring(pos + 1, line.Length - pos - 1).Trim();
if (Value.Length > 0)
{
switch (Identifier)
{
case "ENCODING":
this.Encoding = CEncoding.GetEncoding(Value);
sr = new StreamReader(FilePath, this.Encoding);
Identifier = String.Empty;
line = sr.ReadLine();
while ((line.Length == 0) || (line[0].ToString().Equals("#")) && (Identifier != "ENCODING"))
{
pos = line.IndexOf(":");
if (pos > 0)
{
Identifier = line.Substring(1, pos - 1).Trim().ToUpper();
Value = line.Substring(pos + 1, line.Length - pos - 1).Trim();
}
if (!sr.EndOfStream)
if (Identifier == "ENCODING")
break;
else
line = sr.ReadLine();
else
{
return false;
}
}
break;
case "TITLE":
if (Value != String.Empty)
{
this.Title = Value;
HeaderFlags |= EHeaderFlags.Title;
}
break;
case "ARTIST":
if (Value != String.Empty)
{
this.Artist = Value;
HeaderFlags |= EHeaderFlags.Artist;
}
break;
case "MP3":
if (File.Exists(Path.Combine(this.Folder, Value)))
{
this.MP3FileName = Value;
HeaderFlags |= EHeaderFlags.MP3;
}
break;
case "BPM":
if (CHelper.TryParse(Value, out this.BPM))
{
this.BPM *= 4;
HeaderFlags |= EHeaderFlags.BPM;
}
break;
case "EDITION":
if (Value.Length > 1)
this.Edition.Add(Value);
break;
case "GENRE":
if (Value.Length > 1)
this.Genre.Add(Value);
break;
case "YEAR":
int num = 0;
if (Value.Length == 4 && int.TryParse(Value, out num))
{
this.Year = Value;
}
break;
case "LANGUAGE":
if (Value.Length > 1)
this.Language.Add(Value);
break;
case "COMMENT":
if (Value.Length > 1)
this.Comment.Add(Value);
break;
case "GAP":
if (CHelper.TryParse(Value, out this.Gap))
this.Gap /= 1000f;
break;
case "COVER":
if (File.Exists(Path.Combine(this.Folder, Value)))
this.CoverFileName = Value;
break;
case "BACKGROUND":
if (File.Exists(Path.Combine(this.Folder, Value)))
this.BackgroundFileName = Value;
break;
case "VIDEO":
if (File.Exists(Path.Combine(this.Folder, Value)))
this.VideoFileName = Value;
break;
case "VIDEOGAP":
CHelper.TryParse(Value, out this.VideoGap);
break;
case "VIDEOASPECT":
CHelper.TryParse<EAspect>(Value, out this.VideoAspect, true);
break;
case "START":
CHelper.TryParse(Value, out this.Start);
break;
case "END":
if (CHelper.TryParse(Value, out this.Finish))
this.Finish /= 1000f;
break;
default:
;
break;
}
}
}
if (!sr.EndOfStream)
line = sr.ReadLine();
else
{
return false;
}
} //end of while
if (HeaderFlags != (EHeaderFlags.Title | EHeaderFlags.Artist | EHeaderFlags.MP3 | EHeaderFlags.BPM))
return false;
this.Encoding = sr.CurrentEncoding;
}
catch (Exception)
{
return false;
}
CheckFiles();
return true;
}
public bool ReadNotes()
{
return ReadNotes(Path.Combine(this.Folder, this.FileName));
}
public bool ReadNotes(string FilePath)
{
if (!File.Exists(FilePath))
{
CLog.LogError("Error loading song. The file does not exist: " + FilePath);
return false;
}
char TempC = char.MinValue;
int Param1 = 0;
int Param2 = 0;
int Param3 = 0;
string ParamS = String.Empty;
bool isNewSentence = false;
string line = String.Empty;
int Player = 0;
int FileLineNo = 0;
StreamReader sr;
try
{
sr = new StreamReader(FilePath, this.Encoding, true);
this.Notes.Reset();
//Search for Note Beginning
do
{
line = sr.ReadLine();
FileLineNo++;
if (sr.EndOfStream || (line.Length == 0))
{
CLog.LogError("Error loading song. Line No.: " + FileLineNo.ToString() + ". The file is empty or it starts with an empty line: " + FilePath);
return false;
}
TempC = (char)sr.Read();
} while ((TempC.CompareTo(':') != 0) && (TempC.CompareTo('F') != 0) && (TempC.CompareTo('*') != 0) && (TempC.CompareTo('P') != 0));
FileLineNo++;
while (!sr.EndOfStream && (TempC.CompareTo('E') != 0))
{
if (TempC.CompareTo('P') == 0)
{
char chr = (char)sr.Read();
int.TryParse(chr.ToString(), out Param1);
if (Param1 == 1)
Player = 0;
else if (Param1 == 2)
Player = 1;
else if (Param1 == 3)
Player = 2;
else
{
CLog.LogError("Error loading song. Line No.: " + FileLineNo.ToString() + ". Wrong or missing number after \"P\": " + FilePath);
return false;
}
}
if ((TempC.CompareTo(':') == 0) || (TempC.CompareTo('*') == 0) || (TempC.CompareTo('F') == 0))
{
char chr = (char)sr.Read();
Param1 = CHelper.TryReadInt(sr);
chr = (char)sr.Read();
Param2 = CHelper.TryReadInt(sr);
chr = (char)sr.Read();
Param3 = CHelper.TryReadInt(sr);
chr = (char)sr.Read();
ParamS = sr.ReadLine();
ENoteType NoteType = ENoteType.Normal;
if (TempC.CompareTo('*') == 0)
NoteType = ENoteType.Golden;
if (TempC.CompareTo('F') == 0)
NoteType = ENoteType.Freestyle;
if (Player != 2)
// one singer
ParseNote(Player, NoteType, Param1, Param2, Param3, ParamS);
else
{
// both singer
ParseNote(0, NoteType, Param1, Param2, Param3, ParamS);
ParseNote(1, NoteType, Param1, Param2, Param3, ParamS);
}
isNewSentence = false;
}
if (TempC.CompareTo('-') == 0)
{
if (isNewSentence)
{
CLog.LogError("Error loading song. Line No.: " + FileLineNo.ToString() + ". Double sentence break: " + FilePath);
return false;
}
char chr = (char)sr.Read();
Param1 = CHelper.TryReadInt(sr);
NewSentence(Player, Param1);
isNewSentence = true;
}
int c = 0;
do
{
c = sr.Read();
TempC = (char)c;
} while ((TempC.CompareTo('E') != 0) && !sr.EndOfStream && (c == 19 || c == 16 || c == 13));
}
}
catch (Exception e)
{
CLog.LogError("Error loading song. Line No.: " + FileLineNo.ToString() + ". An unhandled exception occured (" + e.Message + "): " + FilePath);
return false;
}
return true;
}
private void ParseNote(int Player, ENoteType NoteType, int Start, int Length, int Tone, string Text)
{
CNote note = new CNote(Start, Length, Tone, Text, NoteType);
CLines lines = this.Notes.GetLines(Player);
if (lines.LineCount == 0)
{
CLine line = new CLine();
line.AddNote(note);
lines.AddLine(line);
}
else
{
lines.AddNote(note, lines.LineCount - 1);
}
}
private void NewSentence(int Player, int Start)
{
CLines lines = Notes.GetLines(Player);
CLine line = new CLine();
line.StartBeat = Start;
if (lines.LineCount == 0)
{
lines.AddLine(line);
}
else
{
lines.AddLine(line);
}
}
private void CheckFiles()
{
CHelper Helper = new CHelper();
if(this.CoverFileName == String.Empty){
List<string> files = Helper.ListFiles(this.Folder, "*.jpg", false);
files.AddRange(Helper.ListFiles(this.Folder, "*.png", false));
foreach(String file in files)
{
if (Regex.IsMatch(file, @".[CO].", RegexOptions.IgnoreCase) && (Regex.IsMatch(file, @"" + Regex.Escape(this.Title), RegexOptions.IgnoreCase) || Regex.IsMatch(file, @"" + Regex.Escape(this.Artist), RegexOptions.IgnoreCase)))
{
this.CoverFileName = file;
}
}
}
if (this.BackgroundFileName == String.Empty)
{
List<string> files = Helper.ListFiles(this.Folder, "*.jpg", false);
files.AddRange(Helper.ListFiles(this.Folder, "*.png", false));
foreach (String file in files)
{
if (Regex.IsMatch(file, @".[BG].", RegexOptions.IgnoreCase) && (Regex.IsMatch(file, @"" + Regex.Escape(this.Title), RegexOptions.IgnoreCase) || Regex.IsMatch(file, @"" + Regex.Escape(this.Artist), RegexOptions.IgnoreCase)))
{
this.BackgroundFileName = file;
}
}
}
}
}
}
+454
View File
@@ -0,0 +1,454 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using Un4seen.Bass;
using Vocaluxe.Base;
namespace Vocaluxe.Lib.Sound
{
class CBassPlay: IPlayback
{
private bool _Initialized = false;
private List<AudioStreams> _Streams;
private SYNCPROC _SyncSlideAndStop;
private Object MutexAudioStreams = new Object();
public CBassPlay()
{
Init();
}
public bool Init()
{
if (_Initialized)
return true;
#region Registration
string EMail = String.Empty;
string Code = String.Empty;
ReadRegistrationFile(Path.Combine(Environment.CurrentDirectory, CSettings.sBassRegistration), ref EMail, ref Code);
if (EMail == String.Empty || Code == String.Empty)
WriteRegistrationFile(Path.Combine(Environment.CurrentDirectory, CSettings.sBassRegistration), "your mail adress", "your registration code");
else
BassNet.Registration(EMail, Code);
#endregion Registration
bool ok = false;
try
{
ok = Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);
_Streams = new List<AudioStreams>();
_SyncSlideAndStop = new SYNCPROC(EndSync);
}
catch (Exception)
{
ok = false;
}
_Initialized = ok;
return ok;
}
public void CloseAll()
{
while (_Streams.Count > 0)
{
Close(_Streams[_Streams.Count - 1].handle);
}
lock (MutexAudioStreams)
{
_Streams.Clear();
}
}
public void SetGlobalVolume(float Volume)
{
if (_Initialized)
{
Bass.BASS_SetVolume(Volume / 100f);
}
}
public int GetStreamCount()
{
if (!_Initialized)
return 0;
lock (MutexAudioStreams)
{
return _Streams.Count;
}
}
public void Update()
{
}
#region Stream Handling
public int Load(string Media)
{
return Load(Media, false);
}
public int Load(string Media, bool Prescan)
{
if (!_Initialized)
return 0;
BASSFlag flags = BASSFlag.BASS_DEFAULT;
if (Prescan)
flags = BASSFlag.BASS_STREAM_PRESCAN;
AudioStreams stream = new AudioStreams(0);
stream.handle = Bass.BASS_StreamCreateFile(Media, 0L, 0L, flags);
if (stream.handle != 0)
{
stream.file = Media;
lock (MutexAudioStreams)
{
_Streams.Add(stream);
}
return stream.handle;
}
return 0;
}
public void Close(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Bass.BASS_StreamFree(Stream);
_Streams.RemoveAt(GetStreamIndex(Stream));
}
}
}
}
public void Play(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Play(Stream, false);
}
}
}
}
public void Play(int Stream, bool Loop)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
if (Loop)
Bass.BASS_ChannelFlags(Stream, BASSFlag.BASS_SAMPLE_LOOP, BASSFlag.BASS_SAMPLE_LOOP);
Bass.BASS_ChannelPlay(Stream, false);
}
}
}
}
public void Pause(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Bass.BASS_ChannelPause(Stream);
}
}
}
}
public void Stop(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Bass.BASS_ChannelStop(Stream);
}
}
}
}
public void Fade(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Bass.BASS_ChannelSlideAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, TargetVolume/100f, (int)Math.Round(Seconds*1000f));
}
}
}
}
public void FadeAndStop(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Bass.BASS_ChannelSlideAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, TargetVolume / 100f, (int)Math.Round(Seconds * 1000f));
Bass.BASS_ChannelSetSync(Stream, BASSSync.BASS_SYNC_SLIDE, 0L, _SyncSlideAndStop, IntPtr.Zero);
}
}
}
}
public void SetStreamVolume(int Stream, float Volume)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Bass.BASS_ChannelSetAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, Volume / 100f);
}
}
}
}
public float GetLength(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
long len = Bass.BASS_ChannelGetLength(Stream);
return (float)Bass.BASS_ChannelBytes2Seconds(Stream, len);
}
}
return 0f;
}
return 0f;
}
public float GetPosition(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
long pos = Bass.BASS_ChannelGetPosition(Stream);
return (float)Bass.BASS_ChannelBytes2Seconds(Stream, pos);
}
}
return 0f;
}
return 0f;
}
public bool IsPlaying(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
return (Bass.BASS_ChannelIsActive(Stream) == BASSActive.BASS_ACTIVE_PLAYING);
}
}
}
return false;
}
public bool IsPaused(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
return (Bass.BASS_ChannelIsActive(Stream) == BASSActive.BASS_ACTIVE_PAUSED);
}
}
}
return false;
}
public bool IsFinished(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
return (Bass.BASS_ChannelIsActive(Stream) == BASSActive.BASS_ACTIVE_STOPPED);
}
}
}
return true;
}
public void SetPosition(int Stream, float Position)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Bass.BASS_ChannelSetPosition(Stream, Position);
}
}
}
}
#endregion Stream Handling
private bool AlreadyAdded(int Stream)
{
foreach (AudioStreams st in _Streams)
{
if (st.handle == Stream)
{
return true;
}
}
return false;
}
private int GetStreamIndex(int Stream)
{
for (int i = 0; i < _Streams.Count; i++)
{
if (_Streams[i].handle == Stream)
return i;
}
return -1;
}
private void EndSync(int handle, int Stream, int data, IntPtr user)
{
if (_Initialized)
{
if (AlreadyAdded(Stream))
{
Close(Stream);
}
}
}
private void ReadRegistrationFile(string FileName, ref string Email, ref string Code)
{
#region Inits
bool loaded = false;
XPathDocument xPathDoc = null;
XPathNavigator navigator = null;
try
{
xPathDoc = new XPathDocument(FileName);
navigator = xPathDoc.CreateNavigator();
loaded = true;
}
catch (Exception)
{
loaded = false;
if (navigator != null)
navigator = null;
if (xPathDoc != null)
xPathDoc = null;
}
#endregion Inits
if (loaded)
{
CHelper.GetValueFromXML("//root/Registration/EMail", navigator, ref Email, String.Empty);
CHelper.GetValueFromXML("//root/Registration/Code", navigator, ref Code, String.Empty);
}
}
private void WriteRegistrationFile(string FileName, string Email, string Code)
{
XmlWriterSettings _settings = new XmlWriterSettings();
_settings.Indent = true;
_settings.Encoding = Encoding.UTF8;
_settings.ConformanceLevel = ConformanceLevel.Document;
XmlWriter writer;
try
{
writer = XmlWriter.Create(FileName, _settings);
}
catch (Exception)
{
return;
}
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteStartElement("Registration");
writer.WriteComment("Register your BASS.NET version and suppress the freeware splash screen (http://bass.radio42.com/bass_register.html)");
writer.WriteElementString("EMail", Email);
writer.WriteElementString("Code", Code);
writer.WriteEndElement();
// End of File
writer.WriteEndElement(); //end of root
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}
}
+220
View File
@@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Un4seen.Bass;
using Vocaluxe.Base;
namespace Vocaluxe.Lib.Sound
{
class CBassRecord: IRecord
{
private List<SRecordDevice> _Devices = null;
private SRecordDevice[] _DeviceConfig;
private RECORDPROC _myRecProc;
private int[] _recHandle;
private CBuffer[] _Buffer;
public CBassRecord()
{
Init();
_Buffer = new CBuffer[CSettings.MaxNumPlayer];
for (int i = 0; i < _Buffer.Length; i++)
{
_Buffer[i] = new CBuffer();
}
_recHandle = new int[_Devices.Count];
_myRecProc = new RECORDPROC(MyRecording);
_DeviceConfig = _Devices.ToArray();
}
public bool Init()
{
_Devices = new List<SRecordDevice>();
try
{
BASS_DEVICEINFO info = new BASS_DEVICEINFO();
for (int n = 0; Bass.BASS_RecordGetDeviceInfo(n, info); n++)
{
if (info.IsEnabled)
{
SRecordDevice dev = new SRecordDevice();
dev.ID = n;
dev.Name = info.name;
dev.Driver = info.driver;
dev.Inputs = new List<SInput>();
if (Bass.BASS_RecordInit(n))
{
string name = String.Empty;
for (int j = 0; ((name = Bass.BASS_RecordGetInputName(j)) != null); j++)
{
SInput inp = new SInput();
inp.Name = name;
inp.Channels = 2; //TODO: how to retrieve the amount of channels?
dev.Inputs.Add(inp);
}
_Devices.Add(dev);
Bass.BASS_RecordFree();
}
}
}
}
catch (Exception)
{
//throw;
}
return true;
}
public bool Start(SRecordDevice[] DeviceConfig)
{
for (int i = 0; i < _Buffer.Length; i++)
{
_Buffer[i].Reset();
}
for (int i = 0; i < _recHandle.Length; i++)
{
_recHandle[i] = -1;
}
_DeviceConfig = DeviceConfig;
bool[] active = new bool[DeviceConfig.Length];
for (int dev = 0; dev < DeviceConfig.Length; dev++)
{
active[dev] = false;
for (int inp = 0; inp < DeviceConfig[dev].Inputs.Count; inp++)
{
if (DeviceConfig[dev].Inputs[inp].PlayerChannel1 > 0 ||
DeviceConfig[dev].Inputs[inp].PlayerChannel2 > 0)
active[dev] = true;
}
}
bool result = true;
for (int i = 0; i < _recHandle.Length; i++)
{
if (active[i])
{
if (Bass.BASS_RecordInit(i))
{
_recHandle[i] = Bass.BASS_RecordStart(44100, 2, BASSFlag.BASS_RECORD_PAUSE, 20, _myRecProc, IntPtr.Zero);
// start recording
result |= Bass.BASS_ChannelPlay(_recHandle[i], false);
}
}
}
return result;
}
public bool Stop()
{
for (int i = 0; i < _recHandle.Length; i++)
{
Bass.BASS_ChannelStop(_recHandle[i]);
}
Bass.BASS_RecordFree();
//System.IO.File.Delete("test0.raw");
//System.IO.File.Delete("test1.raw");
//System.IO.File.WriteAllBytes("test0.raw", _Buffer[0].Buffer);
//System.IO.File.WriteAllBytes("test1.raw", _Buffer[1].Buffer);
return true;
}
public void CloseAll()
{
Stop();
}
public void AnalyzeBuffer(int Player)
{
_Buffer[Player].AnalyzeBuffer();
}
public int GetToneAbs(int Player)
{
return _Buffer[Player].ToneAbs;
}
public int GetTone(int Player)
{
return _Buffer[Player].Tone;
}
public void SetTone(int Player, int Tone)
{
_Buffer[Player].Tone = Tone;
}
public float GetMaxVolume(int Player)
{
return _Buffer[Player].MaxVolume;
}
public bool ToneValid(int Player)
{
return _Buffer[Player].ToneValid;
}
public SRecordDevice[] RecordDevices()
{
return _Devices.ToArray();
}
private bool MyRecording(int handle, IntPtr buffer, int length, IntPtr user)
{
bool cont = true;
if (length > 0 && buffer != IntPtr.Zero)
{
byte[] _recbuffer = new byte[length];
byte[] _leftBuffer = new byte[length / 2];
byte[] _rightBuffer = new byte[length / 2];
// copy from managed to unmanaged memory
Marshal.Copy(buffer, _recbuffer, 0, length);
// copy into left/right Buffer
for (int i = 0; i < length / 2; i++)
{
_leftBuffer[i] = _recbuffer[i * 2 - (i % 2)];
_rightBuffer[i] = _recbuffer[i * 2 - (i % 2) + 2];
}
for (int i = 0; i < _recHandle.Length; i++)
{
if (_recHandle[i] == handle)
{
if (_DeviceConfig[i].Inputs[0].PlayerChannel1 > 0)
_Buffer[_DeviceConfig[i].Inputs[0].PlayerChannel1 - 1].ProcessNewBuffer(_leftBuffer);
if (_DeviceConfig[i].Inputs[0].PlayerChannel2 > 0)
_Buffer[_DeviceConfig[i].Inputs[0].PlayerChannel2 - 1].ProcessNewBuffer(_rightBuffer);
break;
}
}
}
return cont;
}
}
}
+710
View File
@@ -0,0 +1,710 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using NAudio;
using NAudio.Wave;
using NAudio.CoreAudioApi;
using Vocaluxe.Base;
namespace Vocaluxe.Lib.Sound
{
class NAudioStream
{
const float DELAY = 0.15f;
private string _FileName;
private IWavePlayer _waveOutDevice;
private WaveStream _mainOutputStream;
private WaveChannel32 _volumeStream;
private bool _loaded;
private float _Volume = 1f;
private float _Position = 0f;
private Stopwatch _Timer;
private float _CurrentTime = 0f;
private Stopwatch _fadeTimer;
private float _fadeTime;
private float _targetVolume;
private float _startVolume;
private bool _closeStreamAfterFade = false;
private bool _fading = false;
public int Handle;
public NAudioStream(string FileName)
{
_loaded = false;
_FileName = FileName;
Handle = 0;
_Timer = new Stopwatch();
_fadeTimer = new Stopwatch();
try
{
_waveOutDevice = new WaveOut();
_mainOutputStream = CreateInputStream(FileName);
_waveOutDevice.Init(_mainOutputStream);
}
catch (Exception)
{
_loaded = false;
}
_loaded = true;
}
public void Play()
{
if (_loaded)
{
if (IsPaused())
{
_waveOutDevice.Play();
_Timer.Start();
}
else
{
_waveOutDevice.Play();
Position = _Position;
Volume = _Volume;
_CurrentTime = Position;
_Timer.Start();
}
}
}
public void Stop()
{
if (_loaded)
{
_waveOutDevice.Stop();
_Timer.Stop();
_Timer.Reset();
_Position = 0f;
_CurrentTime = _Position;
}
}
public void Pause()
{
if (_loaded)
{
_waveOutDevice.Pause();
_Timer.Stop();
}
}
public void Close()
{
CloseWaveOut();
_Timer.Stop();
}
public float Length
{
get
{
if (_loaded)
{
TimeSpan tt = _volumeStream.TotalTime;
return (float)tt.TotalSeconds;
}
return 0f;
}
}
public float Position
{
get
{
if (_loaded && _volumeStream != null)
{
TimeSpan tt = _volumeStream.CurrentTime;
float time = (float)tt.TotalSeconds;
if (time != _CurrentTime)
{
_CurrentTime = time;
_Timer.Stop();
_Timer.Reset();
_Timer.Start();
}
else
{
time = _CurrentTime + _Timer.ElapsedMilliseconds / 1000f;
}
//Console.WriteLine(time.ToString("#0.000"));
return time - DELAY;
}
return 0f;
}
set
{
if (_loaded && _volumeStream != null)
{
float pos = value;
if (pos > Length)
pos = Length;
if (pos < 0L)
pos = 0L;
int skip = (int)(pos - _CurrentTime);
_volumeStream.Skip(skip);
_CurrentTime += skip;
}
_Position = value;
}
}
public float Volume
{
get
{
if (_loaded && _volumeStream != null)
{
return _volumeStream.Volume;
}
return 0f;
}
set
{
if (_loaded && _volumeStream != null)
{
float volume = value;
if (volume > 1f)
volume = 1f;
if (volume < 0f)
volume = 0f;
_volumeStream.Volume = volume;
}
_Volume = value;
}
}
public bool IsPlaying()
{
if (_loaded && _waveOutDevice != null)
return _waveOutDevice.PlaybackState == PlaybackState.Playing;
return false;
}
public bool IsPaused()
{
if (_loaded && _waveOutDevice != null)
return _waveOutDevice.PlaybackState == PlaybackState.Paused;
return false;
}
public bool IsFinished()
{
if (_loaded && _waveOutDevice != null)
return _waveOutDevice.PlaybackState == PlaybackState.Stopped;
return false;
}
public bool Update()
{
if (_fading)
{
if ((float)_fadeTimer.ElapsedMilliseconds / 1000f < _fadeTime)
Volume = _startVolume + (_targetVolume - _startVolume) * ((_fadeTimer.ElapsedMilliseconds / 1000f) / _fadeTime);
else
{
Volume = _targetVolume;
_fadeTimer.Stop();
_fading = false;
if (_closeStreamAfterFade)
return false;
}
return true;
}
return true;
}
public void Fade(float TargetVolume, float FadeTime)
{
if (!_loaded || _volumeStream == null)
return;
_fading = true;
_fadeTimer.Stop();
_fadeTimer.Reset();
_startVolume = Volume;
_targetVolume = TargetVolume / 100f;
_fadeTime = FadeTime;
_fadeTimer.Start();
}
public void FadeAndStop(float TargetVolume, float FadeTime)
{
if (!_loaded || _volumeStream == null)
return;
_closeStreamAfterFade = true;
Fade(TargetVolume, FadeTime);
}
private WaveStream CreateInputStream(string fileName)
{
WaveChannel32 inputStream;
if (fileName.EndsWith(".mp3"))
{
WaveStream mp3Reader = new Mp3FileReader(fileName);
inputStream = new WaveChannel32(mp3Reader);
}
else
{
throw new InvalidOperationException("Unsupported extension");
}
_volumeStream = inputStream;
return _volumeStream;
}
private void CloseWaveOut()
{
if (_waveOutDevice != null)
{
_waveOutDevice.Stop();
}
if (_mainOutputStream != null)
{
// this one really closes the file and ACM conversion
_volumeStream.Close();
_volumeStream = null;
// this one does the metering stream
_mainOutputStream.Close();
_mainOutputStream = null;
}
if (_waveOutDevice != null)
{
_waveOutDevice.Dispose();
_waveOutDevice = null;
}
}
}
class CNAudioPlay : IPlayback
{
private bool _Initialized = false;
private int _HandleCounter = 0;
private List<NAudioStream> _Streams;
private Object MutexAudioStreams = new Object();
public CNAudioPlay()
{
Init();
}
public bool Init()
{
if (_Initialized)
{
foreach (NAudioStream stream in _Streams)
{
stream.Close();
}
_Streams.Clear();
_Initialized = false;
}
else
_Streams = new List<NAudioStream>();
_Initialized = true;
return _Initialized;
}
public void CloseAll()
{
while (_Streams.Count > 0)
{
Close(_Streams[_Streams.Count - 1].Handle);
}
lock (MutexAudioStreams)
{
_Streams.Clear();
}
}
public void SetGlobalVolume(float Volume)
{
if (_Initialized)
{
//Bass.BASS_SetVolume(Volume / 100f);
}
}
public int GetStreamCount()
{
if (!_Initialized)
return 0;
lock (MutexAudioStreams)
{
return _Streams.Count;
}
}
public void Update()
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
List<int> StreamsToClose = new List<int>();
for (int i = 0; i < _Streams.Count; i++)
{
if (!_Streams[i].Update())
StreamsToClose.Add(_Streams[i].Handle);
}
foreach (int stream in StreamsToClose)
{
Close(stream);
}
}
}
}
#region Stream Handling
public int Load(string Media)
{
return Load(Media, false);
}
public int Load(string Media, bool Prescan)
{
if (!_Initialized)
return 0;
//BASSFlag flags = BASSFlag.BASS_DEFAULT;
//if (Prescan)
// flags = BASSFlag.BASS_STREAM_PRESCAN;
NAudioStream stream = new NAudioStream(Media);
stream.Handle = ++_HandleCounter;
//stream.handle = Bass.BASS_StreamCreateFile(Media, 0L, 0L, flags);
if (stream.Handle != 0)
{
lock (MutexAudioStreams)
{
_Streams.Add(stream);
}
return stream.Handle;
}
return 0;
}
public void Close(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].Close();
//Bass.BASS_StreamFree(Stream);
_Streams.RemoveAt(index);
}
}
}
}
public void Play(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
Play(Stream, false);
}
}
}
}
public void Play(int Stream, bool Loop)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].Play();
//if (Loop)
//Bass.BASS_ChannelFlags(Stream, BASSFlag.BASS_SAMPLE_LOOP, BASSFlag.BASS_SAMPLE_LOOP);
//Bass.BASS_ChannelPlay(Stream, false);
}
}
}
}
public void Pause(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].Pause();
//Bass.BASS_ChannelPause(Stream);
}
}
}
}
public void Stop(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].Stop();
//Bass.BASS_ChannelStop(Stream);
}
}
}
}
public void Fade(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].Fade(TargetVolume, Seconds);
}
}
}
}
public void FadeAndStop(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
//Stop(Stream);
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].FadeAndStop(TargetVolume, Seconds);
}
}
}
}
public void SetStreamVolume(int Stream, float Volume)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].Volume = Volume / 100f;
//Bass.BASS_ChannelSetAttribute(Stream, BASSAttribute.BASS_ATTRIB_VOL, Volume / 100f);
}
}
}
}
public float GetLength(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
return _Streams[index].Length;
//long len = Bass.BASS_ChannelGetLength(Stream);
//return (float)Bass.BASS_ChannelBytes2Seconds(Stream, len);
}
}
return 0f;
}
return 0f;
}
public float GetPosition(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
return _Streams[index].Position;
//long pos = Bass.BASS_ChannelGetPosition(Stream);
//return (float)Bass.BASS_ChannelBytes2Seconds(Stream, pos);
}
}
return 0f;
}
return 0f;
}
public bool IsPlaying(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
return _Streams[index].IsPlaying();
//return (Bass.BASS_ChannelIsActive(Stream) == BASSActive.BASS_ACTIVE_PLAYING);
}
}
}
return false;
}
public bool IsPaused(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
return _Streams[index].IsPaused();
//return (Bass.BASS_ChannelIsActive(Stream) == BASSActive.BASS_ACTIVE_PAUSED);
}
}
}
return false;
}
public bool IsFinished(int Stream)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
return _Streams[index].IsFinished();
//return (Bass.BASS_ChannelIsActive(Stream) == BASSActive.BASS_ACTIVE_STOPPED);
}
}
}
return true;
}
public void SetPosition(int Stream, float Position)
{
if (_Initialized)
{
lock (MutexAudioStreams)
{
if (AlreadyAdded(Stream))
{
int index = GetStreamIndex(Stream);
_Streams[index].Position = Position;
//Bass.BASS_ChannelSetPosition(Stream, Position);
}
}
}
}
#endregion Stream Handling
private bool AlreadyAdded(int Stream)
{
foreach (NAudioStream st in _Streams)
{
if (st.Handle == Stream)
{
return true;
}
}
return false;
}
private int GetStreamIndex(int Stream)
{
for (int i = 0; i < _Streams.Count; i++)
{
if (_Streams[i].Handle == Stream)
return i;
}
return -1;
}
private void EndSync(int handle, int Stream, int data, IntPtr user)
{
if (_Initialized)
{
if (AlreadyAdded(Stream))
{
Close(Stream);
}
}
}
}
}
+851
View File
@@ -0,0 +1,851 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using OpenTK.Audio;
using Vocaluxe.Base;
using Vocaluxe.Lib.Sound.Decoder;
namespace Vocaluxe.Lib.Sound
{
class COpenALPlay : IPlayback
{
private bool _Initialized = false;
private List<OpenAlStream> _Decoder = new List<OpenAlStream>();
private CLOSEPROC closeproc;
private int _Count = 1;
private AudioContext AC;
private Object MutexDecoder = new Object();
private List<AudioStreams> _Streams;
public COpenALPlay()
{
Init();
}
public bool Init()
{
if (_Initialized)
CloseAll();
AC = new AudioContext();
AC.MakeCurrent();
closeproc = new CLOSEPROC(close_proc);
_Initialized = true;
_Streams = new List<AudioStreams>();
return true;
}
public void CloseAll()
{
lock (MutexDecoder)
{
for (int i = 0; i < _Decoder.Count; i++)
{
_Decoder[i].Free(closeproc, i + 1, MutexDecoder);
}
}
}
public void SetGlobalVolume(float Volume)
{
if (_Initialized)
{
//Bass.BASS_SetVolume(Volume / 100f);
}
}
public int GetStreamCount()
{
if (!_Initialized)
return 0;
lock (MutexDecoder)
{
return _Streams.Count;
}
}
public void Update()
{
if (_Initialized)
{
lock (MutexDecoder)
{
foreach (OpenAlStream stream in _Decoder)
{
stream.UploadData();
}
}
}
}
#region Stream Handling
public int Load(string Media)
{
return Load(Media, false);
}
public int Load(string Media, bool Prescan)
{
AudioStreams stream = new AudioStreams(0);
OpenAlStream decoder = new OpenAlStream();
if (decoder.Open(Media) > -1)
{
lock (MutexDecoder)
{
_Decoder.Add(decoder);
stream.handle = _Count++;
stream.file = Media;
_Streams.Add(stream);
return stream.handle;
}
}
return 0;
}
public void Close(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Free(closeproc, Stream, MutexDecoder);
}
}
}
}
public void Play(int Stream)
{
Play(Stream, false);
}
public void Play(int Stream, bool Loop)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Play();
}
}
}
}
public void Pause(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Paused = true;
}
}
}
}
public void Stop(int Stream)
{
Pause(Stream);
}
public void Fade(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Fade(TargetVolume, Seconds);
}
}
}
}
public void FadeAndStop(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].FadeAndStop(TargetVolume, Seconds, closeproc, Stream);
}
}
}
}
public void SetStreamVolume(int Stream, float Volume)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Volume = Volume;
}
}
}
}
public float GetLength(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Length;
}
}
}
return 0f;
}
public float GetPosition(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Position;
}
}
return 0f;
}
return 0f;
}
public bool IsPlaying(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return !_Decoder[GetStreamIndex(Stream)].Paused && !_Decoder[GetStreamIndex(Stream)].Finished;
}
}
}
return false;
}
public bool IsPaused(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Paused;
}
}
}
return false;
}
public bool IsFinished(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Finished;
}
}
}
return true;
}
public void SetPosition(int Stream, float Position)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Skip(Position);
}
}
}
}
#endregion Stream Handling
private bool AlreadyAdded(int Stream)
{
foreach (AudioStreams st in _Streams)
{
if (st.handle == Stream)
{
return true;
}
}
return false;
}
private int GetStreamIndex(int Stream)
{
for (int i = 0; i < _Streams.Count; i++)
{
if (_Streams[i].handle == Stream)
return i;
}
return -1;
}
private void EndSync(int handle, int Stream, int data, IntPtr user)
{
if (_Initialized)
{
if (AlreadyAdded(Stream))
{
Close(Stream);
}
}
}
private void close_proc(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
int Index = GetStreamIndex(StreamID);
_Decoder.RemoveAt(Index);
_Streams.RemoveAt(Index);
}
}
}
}
}
class OpenAlStream
{
const int buffer_size = 16384;
const int buffer_count = 2;
const long BUFSIZE = 50000L;
Object CloseMutex;
private int[] _buffers;
private int _state;
private int _source;
private FormatInfo _format;
private bool _Initialized;
private int _ByteCount = 4;
private float _Volume = 1f;
private Stopwatch _fadeTimer = new Stopwatch();
private float _fadeTime = 0f;
private float _targetVolume = 1f;
private float _startVolume = 1f;
private bool _closeStreamAfterFade = false;
private bool _fading = false;
private Stopwatch _FadeTimer = new Stopwatch();
private Stopwatch _Timer = new Stopwatch();
private CLOSEPROC _Closeproc;
private int _StreamID;
private string _FileName;
private IAudioDecoder _Decoder;
private float _BytesPerSecond;
private bool _NoMoreData = false;
private bool _FileOpened = false;
private bool _waiting = false;
private bool _skip = false;
private bool _Loop = false;
private float _Duration = 0f;
private float _CurrentTime = 0f;
private float _TimeCode = 0f;
private bool _Paused = false;
private RingBuffer _data;
private float _SetStart = 0f;
private float _Start = 0f;
private bool _SetLoop = false;
private bool _SetSkip = false;
private bool _terminated = false;
private Thread _DecoderThread;
AutoResetEvent EventDecode = new AutoResetEvent(false);
Object MutexData = new Object();
Object MutexSyncSignals = new Object();
public OpenAlStream()
{
_Initialized = false;
_DecoderThread = new Thread(Execute);
}
public void Free(CLOSEPROC close_proc, int StreamID, Object CloseMutex)
{
_Closeproc = close_proc;
_StreamID = StreamID;
_terminated = true;
this.CloseMutex = CloseMutex;
}
public float Length
{
get
{
if (_FileOpened)
return _Duration;
return 0f;
}
}
public bool Finished
{
get
{
lock (MutexData)
{
return _NoMoreData && _data.BytesNotRead == 0L;
}
}
}
public float Volume
{
get { return _Volume * 100f; }
set
{
lock (MutexData)
{
_Volume = value / 100f;
if (_Volume < 0f)
_Volume = 0f;
if (_Volume > 1f)
_Volume = 1f;
}
}
}
public float Position
{
get
{
if (Finished)
_Timer.Stop();
return _CurrentTime + _Timer.ElapsedMilliseconds / 1000f;
}
}
public bool Paused
{
get { return _Paused; }
set
{
_Paused = value;
lock (MutexSyncSignals)
{
if (_Paused)
{
_Timer.Stop();
AL.SourceStop(_source);
}
else
{
_Timer.Start();
EventDecode.Set();
AL.SourcePlay(_source);
}
}
}
}
public void Fade(float TargetVolume, float FadeTime)
{
_fading = true;
_fadeTimer.Stop();
_fadeTimer.Reset();
_startVolume = _Volume;
_targetVolume = TargetVolume / 100f;
_fadeTime = FadeTime;
_fadeTimer.Start();
}
public void FadeAndStop(float TargetVolume, float FadeTime, CLOSEPROC close_proc, int StreamID)
{
_Closeproc = close_proc;
_StreamID = StreamID;
_closeStreamAfterFade = true;
Fade(TargetVolume, FadeTime);
}
public void Play()
{
Paused = false;
AL.SourcePlay(_source);
}
public void Stop()
{
AL.SourceStop(_source);
}
public bool Loop
{
get { return _SetLoop; }
set { _SetLoop = value; }
}
public int Open(string FileName)
{
if (_FileOpened)
return -1;
if (!System.IO.File.Exists(FileName))
return -1;
if (_FileOpened)
return -1;
_Decoder = new CAudioDecoderFFmpeg();
_Decoder.Init();
try
{
_source = AL.GenSource();
_buffers = AL.GenBuffers(buffer_count);
_state = 0;
//AL.SourceQueueBuffers(_source, _buffers.Length, _buffers);
}
catch (Exception)
{
_Initialized = false;
CLog.LogError("Error Init OpenAL Playback");
return -1;
}
_FileName = FileName;
_Decoder.Open(FileName);
_Duration = _Decoder.GetLength();
_format = _Decoder.GetFormatInfo();
_ByteCount = 2 * _format.ChannelCount;
_BytesPerSecond = _format.SamplesPerSecond * _ByteCount;
_CurrentTime = 0f;
_Timer.Reset();
AudioStreams stream = new AudioStreams(0);
stream.handle = _buffers[0];
if (stream.handle != 0)
{
_FileOpened = true;
_data = new RingBuffer(BUFSIZE);
_NoMoreData = false;
_DecoderThread.Priority = ThreadPriority.Normal;
_DecoderThread.Name = Path.GetFileName(FileName);
_DecoderThread.Start();
return stream.handle;
}
return -1;
}
public bool Skip(float Time)
{
lock (MutexSyncSignals)
{
_SetStart = Time;
_SetSkip = true;
}
EventDecode.Set();
return true;
}
#region Threading
private void DoSkip()
{
_Decoder.SetPosition(_Start);
_CurrentTime = _Start;
_TimeCode = _Start;
_Timer.Reset();
_waiting = false;
lock (MutexData)
{
_data = new RingBuffer(BUFSIZE);
_NoMoreData = false;
}
}
private void Execute()
{
while (!_terminated)
{
_waiting = false;
if (EventDecode.WaitOne(1) || !_waiting)
{
if (_skip)
{
DoSkip();
_skip = false;
}
DoDecode();
}
if (!_terminated)
{
lock (MutexSyncSignals)
{
if (_SetSkip)
_skip = true;
_SetSkip = false;
_Start = _SetStart;
_Loop = _SetLoop;
}
}
}
DoFree();
}
private void DoDecode()
{
if (!_FileOpened)
return;
if (_Paused)
return;
if (_terminated)
return;
float Timecode;
byte[] Buffer;
bool DoIt = false;
lock (MutexData)
{
if (BUFSIZE - 10000L > _data.BytesNotRead)
DoIt = true;
}
if (!DoIt)
return;
_Decoder.Decode(out Buffer, out Timecode);
if (Buffer == null)
{
if (_Loop)
{
lock (MutexSyncSignals)
{
_CurrentTime = 0f;
_Start = 0f;
}
DoSkip();
}
else
{
_NoMoreData = true;
}
return;
}
lock (MutexData)
{
_data.Write(Buffer);
_TimeCode = Timecode;
}
}
private void DoFree()
{
if (_Initialized)
{
lock (CloseMutex)
{
Stop();
AL.DeleteSource(_source);
AL.DeleteBuffers(_buffers);
}
}
_Closeproc(_StreamID);
}
#endregion Threading
private void Update()
{
if (_fading)
{
if ((float)_fadeTimer.ElapsedMilliseconds / 1000f < _fadeTime)
_Volume = _startVolume + (_targetVolume - _startVolume) * ((_fadeTimer.ElapsedMilliseconds / 1000f) / _fadeTime);
else
{
_Volume = _targetVolume;
_fadeTimer.Stop();
_fading = false;
if (_closeStreamAfterFade)
_terminated = true;
}
}
}
public void UploadData()
{
Update();
if (_Paused)
return;
int queued_count = 0;
bool doit = true;
AL.GetSource(_source, ALGetSourcei.BuffersQueued, out queued_count);
int processed_count = buffer_count;
if (queued_count != 0)
{
AL.GetSource(_source, ALGetSourcei.BuffersProcessed, out processed_count);
doit = false;
Console.WriteLine("Buffers Prozessed on Stream " + _source.ToString() + " = " + processed_count.ToString());
if (processed_count < 1)
return;
}
byte[] buf = new byte[buffer_size];
lock (MutexData)
{
while (processed_count > 0)
{
if (_data.BytesNotRead >= buf.Length)
{
_data.Read(ref buf);
byte[] b = new byte[2];
for (int i = 0; i < buf.Length; i += _ByteCount)
{
b[0] = buf[i];
b[1] = buf[i + 1];
b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(b, 0) * _Volume));
buf[i] = b[0];
buf[i + 1] = b[1];
if (_ByteCount == 4)
{
b[0] = buf[i + 2];
b[1] = buf[i + 3];
b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(b, 0) * _Volume));
buf[i + 2] = b[0];
buf[i + 3] = b[1];
}
}
int buffer = 0;
if (!doit)
buffer = AL.SourceUnqueueBuffer(_source);
else
{
buffer = _buffers[queued_count];
queued_count++;
}
if (buffer != 0)
{
if (_format.ChannelCount == 2)
AL.BufferData(buffer, ALFormat.Stereo16, buf, buf.Length, _format.SamplesPerSecond);
else
AL.BufferData(buffer, ALFormat.Mono16, buf, buf.Length, _format.SamplesPerSecond);
Console.WriteLine("Write to Buffer: " + buffer.ToString());
AL.SourceQueueBuffer(_source, buffer);
}
}
processed_count--;
}
AL.GetSource(_source, ALGetSourcei.SourceState, out _state);
if ((ALSourceState)_state != ALSourceState.Playing)
{
AL.SourcePlay(_source);
}
}
_CurrentTime = _TimeCode - _data.BytesNotRead / _BytesPerSecond - 0.1f;
_Timer.Reset();
_Timer.Start();
}
}
}
+10
View File
@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Lib.Sound
{
class COpenALRecord
{
}
}
+896
View File
@@ -0,0 +1,896 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using PortAudioSharp;
using Vocaluxe.Base;
using Vocaluxe.Lib.Sound.Decoder;
namespace Vocaluxe.Lib.Sound
{
class CPortAudioPlay : IPlayback
{
private bool _Initialized = false;
private List<PortAudioStream> _Decoder = new List<PortAudioStream>();
private CLOSEPROC closeproc;
private int _Count = 1;
private Object MutexDecoder = new Object();
private List<AudioStreams> _Streams;
public CPortAudioPlay()
{
Init();
}
public bool Init()
{
if (_Initialized)
CloseAll();
closeproc = new CLOSEPROC(close_proc);
_Initialized = true;
_Streams = new List<AudioStreams>();
return true;
}
public void CloseAll()
{
lock (MutexDecoder)
{
for (int i = 0; i < _Decoder.Count; i++)
{
_Decoder[i].Free(closeproc, i + 1);
}
}
}
public void SetGlobalVolume(float Volume)
{
if (_Initialized)
{
//Bass.BASS_SetVolume(Volume / 100f);
}
}
public int GetStreamCount()
{
if (!_Initialized)
return 0;
lock (MutexDecoder)
{
return _Streams.Count;
}
}
public void Update()
{
}
#region Stream Handling
public int Load(string Media)
{
return Load(Media, false);
}
public int Load(string Media, bool Prescan)
{
AudioStreams stream = new AudioStreams(0);
PortAudioStream decoder = new PortAudioStream();
if (decoder.Open(Media) > -1)
{
lock (MutexDecoder)
{
_Decoder.Add(decoder);
stream.handle = _Count++;
stream.file = Media;
_Streams.Add(stream);
return stream.handle;
}
}
return 0;
}
public void Close(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Free(closeproc, Stream);
}
}
}
}
public void Play(int Stream)
{
Play(Stream, false);
}
public void Play(int Stream, bool Loop)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Play();
}
}
}
}
public void Pause(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Paused = true;
}
}
}
}
public void Stop(int Stream)
{
Pause(Stream);
}
public void Fade(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Fade(TargetVolume, Seconds);
}
}
}
}
public void FadeAndStop(int Stream, float TargetVolume, float Seconds)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].FadeAndStop(TargetVolume, Seconds, closeproc, Stream);
}
}
}
}
public void SetStreamVolume(int Stream, float Volume)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Volume = Volume;
}
}
}
}
public float GetLength(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Length;
}
}
}
return 0f;
}
public float GetPosition(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Position;
}
}
return 0f;
}
return 0f;
}
public bool IsPlaying(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return !_Decoder[GetStreamIndex(Stream)].Paused && !_Decoder[GetStreamIndex(Stream)].Finished;
}
}
}
return false;
}
public bool IsPaused(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Paused;
}
}
}
return false;
}
public bool IsFinished(int Stream)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
return _Decoder[GetStreamIndex(Stream)].Finished;
}
}
}
return true;
}
public void SetPosition(int Stream, float Position)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(Stream))
{
_Decoder[GetStreamIndex(Stream)].Skip(Position);
}
}
}
}
#endregion Stream Handling
private bool AlreadyAdded(int Stream)
{
foreach (AudioStreams st in _Streams)
{
if (st.handle == Stream)
{
return true;
}
}
return false;
}
private int GetStreamIndex(int Stream)
{
for (int i = 0; i < _Streams.Count; i++)
{
if (_Streams[i].handle == Stream)
return i;
}
return -1;
}
private void EndSync(int handle, int Stream, int data, IntPtr user)
{
if (_Initialized)
{
if (AlreadyAdded(Stream))
{
Close(Stream);
}
}
}
private void close_proc(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
int Index = GetStreamIndex(StreamID);
_Decoder.RemoveAt(Index);
_Streams.RemoveAt(Index);
}
}
}
}
}
class PortAudioStream
{
const long BUFSIZE = 50000L;
private CSyncTimer _SyncTimer;
private bool _Initialized;
private int _ByteCount = 4;
private float _Volume = 1f;
private Stopwatch _fadeTimer = new Stopwatch();
private float _fadeTime = 0f;
private float _targetVolume = 1f;
private float _startVolume = 1f;
private bool _closeStreamAfterFade = false;
private bool _fading = false;
private PortAudio.PaHostApiInfo _apiInfo;
private PortAudio.PaDeviceInfo _outputDeviceInfo;
private IntPtr _Ptr = new IntPtr(0);
private Stopwatch _FadeTimer = new Stopwatch();
private CLOSEPROC _Closeproc;
private PortAudio.PaStreamCallbackDelegate _paStreamCallback;
private int _StreamID;
private string _FileName;
private IAudioDecoder _Decoder;
private float _BytesPerSecond;
private bool _NoMoreData = false;
private bool _FileOpened = false;
private bool _waiting = false;
private bool _skip = false;
private bool _Loop = false;
private float _Duration = 0f;
private float _CurrentTime = 0f;
private float _TimeCode = 0f;
private bool _Paused = false;
private RingBuffer _data;
private float _SetStart = 0f;
private float _Start = 0f;
private bool _SetLoop = false;
private bool _SetSkip = false;
private bool _terminated = false;
private Thread _DecoderThread;
AutoResetEvent EventDecode = new AutoResetEvent(false);
Object MutexData = new Object();
Object MutexSyncSignals = new Object();
public PortAudioStream()
{
_Initialized = false;
_SyncTimer = new CSyncTimer(0f, 1f, 0.02f);
_DecoderThread = new Thread(Execute);
}
public void Free(CLOSEPROC close_proc, int StreamID)
{
_Closeproc = close_proc;
_StreamID = StreamID;
_terminated = true;
}
public float Length
{
get
{
if (_FileOpened)
return _Duration;
return 0f;
}
}
public bool Finished
{
get
{
lock (MutexData)
{
return _NoMoreData && _data.BytesNotRead == 0L;
}
}
}
public float Volume
{
get { return _Volume * 100f; }
set
{
lock (MutexData)
{
_Volume = value / 100f;
if (_Volume < 0f)
_Volume = 0f;
if (_Volume > 1f)
_Volume = 1f;
}
}
}
public float Position
{
get
{
lock (MutexData)
{
if (Finished)
_SyncTimer.Pause();
return _SyncTimer.Time;
}
}
}
public bool Paused
{
get { return _Paused; }
set
{
_Paused = value;
lock (MutexSyncSignals)
{
if (_Paused)
_SyncTimer.Pause();
else
{
_SyncTimer.Resume();
EventDecode.Set();
}
}
}
}
public void Fade(float TargetVolume, float FadeTime)
{
_fading = true;
_fadeTimer.Stop();
_fadeTimer.Reset();
_startVolume = _Volume;
_targetVolume = TargetVolume / 100f;
_fadeTime = FadeTime;
_fadeTimer.Start();
}
public void FadeAndStop(float TargetVolume, float FadeTime, CLOSEPROC close_proc, int StreamID)
{
_Closeproc = close_proc;
_StreamID = StreamID;
_closeStreamAfterFade = true;
Fade(TargetVolume, FadeTime);
}
public void Play()
{
Paused = false;
errorCheck("StartStream", PortAudio.Pa_StartStream(_Ptr));
}
public void Stop()
{
errorCheck("StartStream", PortAudio.Pa_StopStream(_Ptr));
}
public bool Loop
{
get { return _SetLoop; }
set { _SetLoop = value; }
}
public int Open(string FileName)
{
if (_FileOpened)
return -1;
if (!System.IO.File.Exists(FileName))
return -1;
if (_FileOpened)
return -1;
_Decoder = new CAudioDecoderFFmpeg();
_Decoder.Init();
try
{
if (errorCheck("Initialize", PortAudio.Pa_Initialize()))
return -1;
_Initialized = true;
int hostApi = apiSelect();
_apiInfo = PortAudio.Pa_GetHostApiInfo(hostApi);
_outputDeviceInfo = PortAudio.Pa_GetDeviceInfo(_apiInfo.defaultOutputDevice);
_paStreamCallback = new PortAudio.PaStreamCallbackDelegate(_PaStreamCallback);
if (_outputDeviceInfo.defaultLowOutputLatency < 0.1)
_outputDeviceInfo.defaultLowOutputLatency = 0.1;
}
catch (Exception)
{
_Initialized = false;
CLog.LogError("Error Init PortAudio Playback");
return -1;
}
_FileName = FileName;
_Decoder.Open(FileName);
_Duration = _Decoder.GetLength();
FormatInfo format = _Decoder.GetFormatInfo();
_ByteCount = 2 * format.ChannelCount;
_BytesPerSecond = format.SamplesPerSecond * _ByteCount;
_CurrentTime = 0f;
_SyncTimer.Time = _CurrentTime;
AudioStreams stream = new AudioStreams(0);
IntPtr data = new IntPtr(0);
PortAudio.PaStreamParameters outputParams = new PortAudio.PaStreamParameters();
outputParams.channelCount = format.ChannelCount;
outputParams.device = _apiInfo.defaultOutputDevice;
outputParams.sampleFormat = PortAudio.PaSampleFormat.paInt16;
outputParams.suggestedLatency = _outputDeviceInfo.defaultLowOutputLatency;
errorCheck("OpenDefaultStream", PortAudio.Pa_OpenStream(
out _Ptr,
IntPtr.Zero,
ref outputParams,
format.SamplesPerSecond,
0,//CConfig.PortAudioBufferSize,
PortAudio.PaStreamFlags.paNoFlag,
_paStreamCallback,
data));
stream.handle = _Ptr.ToInt32();
if (stream.handle != 0)
{
_Paused = true;
_waiting = true;
_FileOpened = true;
_data = new RingBuffer(BUFSIZE);
_NoMoreData = false;
_DecoderThread.Priority = ThreadPriority.Normal;
_DecoderThread.Name = Path.GetFileName(FileName);
_DecoderThread.Start();
return stream.handle;
}
return -1;
}
public bool Skip(float Time)
{
lock (MutexSyncSignals)
{
_SetStart = Time;
_SetSkip = true;
_waiting = true;
}
return true;
}
#region Threading
private void DoSkip()
{
lock (MutexData)
{
_Decoder.SetPosition(_Start);
_CurrentTime = _Start;
_TimeCode = _Start;
_data = new RingBuffer(BUFSIZE);
_NoMoreData = false;
EventDecode.Set();
_waiting = false;
_SyncTimer.Time = _Start;
}
}
private void Execute()
{
while (!_terminated)
{
if (EventDecode.WaitOne(10))
{
if (_skip)
{
DoSkip();
_skip = false;
}
if (!_waiting)
{
DoDecode();
Update();
}
}
if (!_terminated)
{
lock (MutexSyncSignals)
{
if (_SetSkip)
{
_skip = true;
EventDecode.Set();
_waiting = true;
}
_SetSkip = false;
_Start = _SetStart;
_Loop = _SetLoop;
}
}
}
DoFree();
}
private void DoDecode()
{
if (!_FileOpened)
return;
if (_Paused)
return;
if (_terminated)
return;
float Timecode;
byte[] Buffer;
bool DoIt = false;
lock (MutexData)
{
if (!_skip && BUFSIZE - 10000L > _data.BytesNotRead)
DoIt = true;
}
if (!DoIt)
return;
_Decoder.Decode(out Buffer, out Timecode);
if (Buffer == null)
{
if (_Loop)
{
lock (MutexSyncSignals)
{
_CurrentTime = 0f;
_Start = 0f;
}
DoSkip();
}
else
{
_NoMoreData = true;
}
return;
}
lock (MutexData)
{
_data.Write(Buffer);
_TimeCode = Timecode;
if (_data.BytesNotRead < BUFSIZE - 10000L)
{
_waiting = false;
EventDecode.Set();
}
else
_waiting = true;
}
}
private void DoFree()
{
if (_Initialized)
{
Stop();
PortAudio.Pa_Terminate();
}
_Closeproc(_StreamID);
}
#endregion Threading
#region Callbacks
private PortAudio.PaStreamCallbackResult _PaStreamCallback(
IntPtr input,
IntPtr output,
uint frameCount,
ref PortAudio.PaStreamCallbackTimeInfo timeInfo,
PortAudio.PaStreamCallbackFlags statusFlags,
IntPtr userData)
{
byte[] buf = new byte[frameCount * _ByteCount];
if (_Paused)
{
try
{
Marshal.Copy(buf, 0, output, (int)frameCount * _ByteCount);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return PortAudio.PaStreamCallbackResult.paContinue;
}
lock (MutexData)
{
if (_NoMoreData || _data.BytesNotRead >= buf.Length)
{
_data.Read(ref buf);
byte[] b = new byte[2];
for (int i = 0; i < buf.Length; i += _ByteCount)
{
b[0] = buf[i];
b[1] = buf[i + 1];
b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(b, 0) * _Volume));
buf[i] = b[0];
buf[i + 1] = b[1];
if (_ByteCount == 4)
{
b[0] = buf[i + 2];
b[1] = buf[i + 3];
b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(b, 0) * _Volume));
buf[i + 2] = b[0];
buf[i + 3] = b[1];
}
}
}
if (_data.BytesNotRead < BUFSIZE - 10000L)
{
EventDecode.Set();
_waiting = false;
}
else
_waiting = true;
float latency = buf.Length / _BytesPerSecond;
float time = _TimeCode - _data.BytesNotRead / _BytesPerSecond - latency;
_CurrentTime = _SyncTimer.Update(time);
}
try
{
Marshal.Copy(buf, 0, output, (int)frameCount * _ByteCount);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return PortAudio.PaStreamCallbackResult.paContinue;
}
#endregion Callbacks
private bool errorCheck(String action, PortAudio.PaError errorCode)
{
if (errorCode != PortAudio.PaError.paNoError)
{
if (errorCode == PortAudio.PaError.paStreamIsNotStopped)
return false;
CLog.LogError(action + " error: " + PortAudio.Pa_GetErrorText(errorCode));
if (errorCode == PortAudio.PaError.paUnanticipatedHostError)
{
PortAudio.PaHostErrorInfo errorInfo = PortAudio.Pa_GetLastHostErrorInfo();
CLog.LogError("- Host error API type: " + errorInfo.hostApiType);
CLog.LogError("- Host error code: " + errorInfo.errorCode);
CLog.LogError("- Host error text: " + errorInfo.errorText);
}
return true;
}
return false;
}
private int apiSelect()
{
if (!_Initialized)
return 0;
int selectedHostApi = PortAudio.Pa_GetDefaultHostApi();
int apiCount = PortAudio.Pa_GetHostApiCount();
for (int i = 0; i < apiCount; i++)
{
PortAudio.PaHostApiInfo apiInfo = PortAudio.Pa_GetHostApiInfo(i);
if ((apiInfo.type == PortAudio.PaHostApiTypeId.paDirectSound)
|| (apiInfo.type == PortAudio.PaHostApiTypeId.paALSA))
selectedHostApi = i;
}
return selectedHostApi;
}
private void Update()
{
if (_fading)
{
if ((float)_fadeTimer.ElapsedMilliseconds / 1000f < _fadeTime)
_Volume = _startVolume + (_targetVolume - _startVolume) * ((_fadeTimer.ElapsedMilliseconds / 1000f) / _fadeTime);
else
{
_Volume = _targetVolume;
_fadeTimer.Stop();
_fading = false;
if (_closeStreamAfterFade)
_terminated = true;
}
}
}
}
}
+336
View File
@@ -0,0 +1,336 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using PortAudioSharp;
using Vocaluxe.Base;
namespace Vocaluxe.Lib.Sound
{
class CPortAudioRecord : IRecord
{
private bool _initialized = false;
private List<SRecordDevice> _Devices = null;
private SRecordDevice[] _DeviceConfig;
private PortAudio.PaStreamCallbackDelegate _myRecProc;
private IntPtr[] _recHandle;
private CBuffer[] _Buffer;
public CPortAudioRecord()
{
_DeviceConfig = null;
_Buffer = new CBuffer[CSettings.MaxNumPlayer];
for (int i = 0; i < _Buffer.Length; i++)
{
_Buffer[i] = new CBuffer();
}
Init();
}
/// <summary>
/// Init PortAudio and list record devices
/// </summary>
/// <returns>true if success</returns>
public bool Init()
{
_Devices = new List<SRecordDevice>();
try
{
if (_initialized)
CloseAll();
if (errorCheck("Initialize", PortAudio.Pa_Initialize()))
return false;
_initialized = true;
int hostAPI = apiSelect();
int numDevices = PortAudio.Pa_GetDeviceCount();
for (int i = 0; i < numDevices; i++)
{
PortAudio.PaDeviceInfo info = PortAudio.Pa_GetDeviceInfo(i);
if (info.hostApi == hostAPI && info.maxInputChannels > 0)
{
SRecordDevice dev = new SRecordDevice();
dev.ID = i;
dev.Name = info.name;
dev.Driver = info.name + i.ToString();
dev.Inputs = new List<SInput>();
SInput inp = new SInput();
inp.Name = "Default";
inp.Channels = info.maxInputChannels;
if (inp.Channels > 2)
inp.Channels = 2; //more are not supported in vocaluxe
dev.Inputs.Add(inp);
_Devices.Add(dev);
}
}
_recHandle = new IntPtr[_Devices.Count];
_myRecProc = new PortAudio.PaStreamCallbackDelegate(myPaStreamCallback);
_DeviceConfig = _Devices.ToArray();
}
catch (Exception)
{
_initialized = false;
CLog.LogError("Error initializing PortAudio");
return false;
}
return true;
}
/// <summary>
/// Start Voice Capturing
/// </summary>
/// <param name="DeviceConfig"></param>
/// <returns></returns>
public bool Start(SRecordDevice[] DeviceConfig)
{
if (!_initialized)
return false;
for (int i = 0; i < _Buffer.Length; i++)
{
_Buffer[i].Reset();
}
for (int i = 0; i < _recHandle.Length; i++)
{
_recHandle[i] = IntPtr.Zero;
}
_DeviceConfig = DeviceConfig;
bool[] active = new bool[DeviceConfig.Length];
for (int dev = 0; dev < DeviceConfig.Length; dev++)
{
active[dev] = false;
for (int inp = 0; inp < DeviceConfig[dev].Inputs.Count; inp++)
{
if (DeviceConfig[dev].Inputs[inp].PlayerChannel1 > 0 ||
DeviceConfig[dev].Inputs[inp].PlayerChannel2 > 0)
active[dev] = true;
}
}
bool result = true;
for (int i = 0; i < _recHandle.Length; i++)
{
if (active[i])
{
PortAudio.PaStreamParameters inputParams = new PortAudio.PaStreamParameters();
inputParams.channelCount = _DeviceConfig[i].Inputs[0].Channels;
inputParams.device = _DeviceConfig[i].ID;
inputParams.sampleFormat = PortAudio.PaSampleFormat.paInt16;
inputParams.suggestedLatency = PortAudio.Pa_GetDeviceInfo(_DeviceConfig[i].ID).defaultLowInputLatency;
if (errorCheck("OpenStream", PortAudio.Pa_OpenStream(
out _recHandle[i],
ref inputParams,
IntPtr.Zero,
44100,
PortAudio.paFramesPerBufferUnspecified,
PortAudio.PaStreamFlags.paNoFlag,
_myRecProc,
new IntPtr(i))))
return false;
if (errorCheck("Start Stream", PortAudio.Pa_StartStream(_recHandle[i])))
return false;
}
}
return result;
}
/// <summary>
/// Stop Voice Capturing
/// </summary>
/// <returns></returns>
public bool Stop()
{
if (!_initialized)
return false;
for (int i = 0; i < _recHandle.Length; i++)
{
PortAudio.Pa_StopStream(_recHandle[i]);
}
return true;
}
/// <summary>
/// Stop all voice capturing streams and terminate PortAudio
/// </summary>
public void CloseAll()
{
Stop();
if (_initialized)
{
PortAudio.Pa_Terminate();
_initialized = false;
}
//System.IO.File.WriteAllBytes("test0.raw", _Buffer[0].Buffer);
}
/// <summary>
/// Detect Pitch and Volume of the newest voice buffer
/// </summary>
/// <param name="Player"></param>
public void AnalyzeBuffer(int Player)
{
if (!_initialized)
return;
_Buffer[Player].AnalyzeBuffer();
}
public int GetToneAbs(int Player)
{
if (!_initialized)
return 0;
return _Buffer[Player].ToneAbs;
}
public int GetTone(int Player)
{
if (!_initialized)
return 0;
return _Buffer[Player].Tone;
}
public void SetTone(int Player, int Tone)
{
if (!_initialized)
return;
_Buffer[Player].Tone = Tone;
}
public float GetMaxVolume(int Player)
{
if (!_initialized)
return 0f;
return _Buffer[Player].MaxVolume;
}
public bool ToneValid(int Player)
{
if (!_initialized)
return false;
return _Buffer[Player].ToneValid;
}
public SRecordDevice[] RecordDevices()
{
if (!_initialized)
return null;
return _Devices.ToArray();
}
public PortAudio.PaStreamCallbackResult myPaStreamCallback(
IntPtr input,
IntPtr output,
uint frameCount,
ref PortAudio.PaStreamCallbackTimeInfo timeInfo,
PortAudio.PaStreamCallbackFlags statusFlags,
IntPtr userData)
{
try
{
frameCount *= 4;
if (frameCount > 0 && input != IntPtr.Zero)
{
byte[] _recbuffer = new byte[frameCount];
byte[] _leftBuffer = new byte[frameCount / 2];
byte[] _rightBuffer = new byte[frameCount / 2];
// copy from managed to unmanaged memory
Marshal.Copy(input, _recbuffer, 0, (int)frameCount);
// copy into left/right Buffer
for (int i = 0; i < frameCount / 2; i++)
{
_leftBuffer[i] = _recbuffer[i * 2 - (i % 2)];
_rightBuffer[i] = _recbuffer[i * 2 - (i % 2) + 2];
}
for (int i = 0; i < _recHandle.Length; i++)
{
if (new IntPtr(i) == userData)
{
if (_DeviceConfig[i].Inputs[0].PlayerChannel1 > 0)
_Buffer[_DeviceConfig[i].Inputs[0].PlayerChannel1 - 1].ProcessNewBuffer(_leftBuffer);
if (_DeviceConfig[i].Inputs[0].PlayerChannel2 > 0)
_Buffer[_DeviceConfig[i].Inputs[0].PlayerChannel2 - 1].ProcessNewBuffer(_rightBuffer);
break;
}
}
}
}
catch (Exception e)
{
CLog.LogError("Error on Stream Callback: " + e.ToString());
}
return PortAudio.PaStreamCallbackResult.paContinue;
}
private bool errorCheck(String action, PortAudio.PaError errorCode)
{
if (errorCode != PortAudio.PaError.paNoError)
{
CLog.LogError(action + " error: " + PortAudio.Pa_GetErrorText(errorCode));
if (errorCode == PortAudio.PaError.paUnanticipatedHostError)
{
PortAudio.PaHostErrorInfo errorInfo = PortAudio.Pa_GetLastHostErrorInfo();
CLog.LogError("- Host error API type: " + errorInfo.hostApiType);
CLog.LogError("- Host error code: " + errorInfo.errorCode);
CLog.LogError("- Host error text: " + errorInfo.errorText);
}
return true;
}
return false;
}
private int apiSelect()
{
if (!_initialized)
return 0;
int selectedHostApi = PortAudio.Pa_GetDefaultHostApi();
int apiCount = PortAudio.Pa_GetHostApiCount();
for (int i = 0; i < apiCount; i++)
{
PortAudio.PaHostApiInfo apiInfo = PortAudio.Pa_GetHostApiInfo(i);
if ((apiInfo.type == PortAudio.PaHostApiTypeId.paDirectSound)
|| (apiInfo.type == PortAudio.PaHostApiTypeId.paALSA))
selectedHostApi = i;
}
return selectedHostApi;
}
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Lib.Sound.Decoder
{
abstract class CAudioDecoder: IAudioDecoder
{
protected bool _Initialized;
public virtual void Init()
{
}
public virtual void Close()
{
}
public void Open(string FileName)
{
Open(FileName, false);
}
public virtual void Open(string FileName, bool Loop)
{
}
public virtual FormatInfo GetFormatInfo()
{
return new FormatInfo();
}
public virtual float GetLength()
{
return 0f;
}
public virtual void SetPosition(float Time)
{
}
public virtual float GetPosition()
{
return 0f;
}
public virtual void Decode(out byte[] Buffer, out float TimeStamp)
{
Buffer = null;
TimeStamp = 0f;
}
}
}
@@ -0,0 +1,223 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Vocaluxe.Base;
using Vocaluxe.Lib.Video.Acinerella;
namespace Vocaluxe.Lib.Sound.Decoder
{
class CAudioDecoderFFmpeg: CAudioDecoder
{
private TAc_read_callback _rc;
private TAc_seek_callback _sc;
private FileStream _fs;
private IntPtr _instance = IntPtr.Zero;
private IntPtr _audiodecoder = IntPtr.Zero;
private TAc_instance _Instance;
private FormatInfo _FormatInfo;
private float _CurrentTime;
private string _FileName;
private bool _FileOpened = false;
public override void Init()
{
_rc = new TAc_read_callback(read_proc);
_sc = new TAc_seek_callback(seek_proc);
_FileOpened = false;
_Initialized = true;
}
public override void Open(string FileName, bool Loop)
{
if (!_Initialized)
return;
_FileName = FileName;
_fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
_instance = CAcinerella.ac_init();
CAcinerella.ac_open(_instance, IntPtr.Zero, null, _rc, _sc, null, IntPtr.Zero);
_Instance = (TAc_instance)Marshal.PtrToStructure(_instance, typeof(TAc_instance));
if (!_Instance.opened)
{
//Free();
return;
}
int AudioStreamIndex = -1;
TAc_stream_info Info = new TAc_stream_info();
for (int i = 0; i < _Instance.stream_count; i++)
{
CAcinerella.ac_get_stream_info(_instance, i, out Info);
if (Info.stream_type == TAc_stream_type.AC_STREAM_TYPE_AUDIO)
{
try
{
_audiodecoder = CAcinerella.ac_create_decoder(_instance, i);
}
catch (Exception)
{
return;
}
AudioStreamIndex = i;
break;
}
}
if (AudioStreamIndex < 0)
{
//Free();
return;
}
TAc_decoder Audiodecoder = (TAc_decoder)Marshal.PtrToStructure(_audiodecoder, typeof(TAc_decoder));
_FormatInfo = new FormatInfo();
_FormatInfo.SamplesPerSecond = Audiodecoder.stream_info.audio_info.samples_per_second;
_FormatInfo.BitDepth = Audiodecoder.stream_info.audio_info.bit_depth;
_FormatInfo.ChannelCount = Audiodecoder.stream_info.audio_info.channel_count;
_CurrentTime = 0f;
if (_FormatInfo.BitDepth != 16)
{
CLog.LogError("Unsupported BitDepth in file " + FileName);
return;
}
_FileOpened = true;
}
public override void Close()
{
if (!_Initialized)
return;
_Initialized = false;
if (!_FileOpened)
return;
if (_audiodecoder != IntPtr.Zero)
CAcinerella.ac_free_decoder(_audiodecoder);
if (_instance != IntPtr.Zero)
CAcinerella.ac_close(_instance);
if (_instance != IntPtr.Zero)
CAcinerella.ac_free(_instance);
_FileOpened = false;
}
public override FormatInfo GetFormatInfo()
{
if (!_Initialized && !_FileOpened)
return new FormatInfo();
return _FormatInfo;
}
public override float GetLength()
{
if (!_Initialized && !_FileOpened)
return 0f;
return (float)_Instance.info.duration / 1000f; ;
}
public override void SetPosition(float Time)
{
if (!_Initialized && !_FileOpened)
return;
try
{
CAcinerella.ac_seek(_audiodecoder, 0, (Int64)(Time * 1000f));
}
catch (Exception)
{
CLog.LogError("Error seeking in file: " + _FileName);
Close();
}
}
public override float GetPosition()
{
if (!_Initialized && !_FileOpened)
return 0f;
return _CurrentTime;
}
public override void Decode(out byte[] Buffer, out float TimeStamp)
{
if (!_Initialized && !_FileOpened)
{
Buffer = null;
TimeStamp = 0f;
return;
}
int FrameFinished = 0;
try
{
FrameFinished = CAcinerella.ac_get_audio_frame(_instance, _audiodecoder);
}
catch (Exception)
{
FrameFinished = 0;
}
if (FrameFinished == 1)
{
TAc_decoder Decoder = (TAc_decoder)Marshal.PtrToStructure(_audiodecoder, typeof(TAc_decoder));
TimeStamp = (float)Decoder.timecode;
_CurrentTime = TimeStamp;
//Console.WriteLine(_CurrentTime.ToString("#0.000") + " Buffer size: " + Decoder.buffer_size.ToString());
Buffer = new byte[Decoder.buffer_size];
if (Decoder.buffer_size > 0)
Marshal.Copy(Decoder.buffer, Buffer, 0, Buffer.Length);
return;
}
Buffer = null;
TimeStamp = 0f;
}
#region Callbacks
private Int32 read_proc(IntPtr sender, IntPtr buf, Int32 size)
{
Int32 r = 0;
byte[] bb = new byte[size];
r = _fs.Read(bb, 0, size);
Marshal.Copy(bb, 0, buf, size);
return r;
}
private Int64 seek_proc(IntPtr sender, Int64 pos, Int32 whence)
{
return (Int64)_fs.Seek((long)pos, (SeekOrigin)whence);
}
#endregion Callbacks
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Lib.Sound.Decoder
{
struct FormatInfo
{
public int ChannelCount;
public int SamplesPerSecond;
public int BitDepth;
}
interface IAudioDecoder
{
void Init();
void Close();
void Open(string FileName);
void Open(string FileName, bool Loop);
FormatInfo GetFormatInfo();
float GetLength();
void SetPosition(float Time);
float GetPosition();
void Decode(out byte[] Buffer, out float TimeStamp);
}
}
+109
View File
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Lib.Sound
{
struct AudioStreams
{
public int handle;
public string file;
public AudioStreams(int stream)
{
handle = stream;
file = String.Empty;
}
}
delegate void CLOSEPROC(int StreamID);
interface IPlayback
{
bool Init();
void SetGlobalVolume(float Volume);
int GetStreamCount();
void CloseAll();
#region Stream Handling
int Load(string Media);
int Load(string Media, bool Prescan);
void Close(int Stream);
void Play(int Stream);
void Play(int Stream, bool Loop);
void Pause(int Stream);
void Stop(int Stream);
void Fade(int Stream, float TargetVolume, float Seconds);
void FadeAndStop(int Stream, float TargetVolume, float Seconds);
void SetStreamVolume(int Stream, float Volume);
float GetLength(int Stream);
float GetPosition(int Stream);
bool IsPlaying(int Stream);
bool IsPaused(int Stream);
bool IsFinished(int Stream);
void SetPosition(int Stream, float Position);
void Update();
#endregion Stream Handling
}
class RingBuffer
{
private byte[] _data;
private long _size;
private long _readPos;
private long _writePos;
private long _bytesNotRead;
public long BytesNotRead
{
get
{
return _bytesNotRead;
}
}
public RingBuffer(long size)
{
_size = size;
_data = new byte[size];
_readPos = 0L;
_writePos = 0L;
_bytesNotRead = 0L;
}
public void Write(byte[] Data)
{
long written = 0L;
while (written < Data.Length)
{
_data[_writePos] = Data[written];
_writePos++;
if (_writePos >= _size)
_writePos = 0L;
written++;
_bytesNotRead++;
}
}
public void Read(ref byte[] Data)
{
long read = 0L;
while (read < Data.Length && _bytesNotRead > 0L)
{
Data[read] = _data[_readPos];
_readPos++;
if (_readPos >= _size)
_readPos = 0L;
read++;
_bytesNotRead--;
}
}
}
}
+57
View File
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Lib.Sound
{
struct SRecordDevice
{
public int ID;
public string Name;
public string Driver;
public List<SInput> Inputs;
}
struct SInput
{
public string Name;
public int Channels;
public int PlayerChannel1;
public int PlayerChannel2;
}
struct SMicConfig
{
public string DeviceName;
public string DeviceDriver;
public string InputName;
public int Channel;
public SMicConfig(int dummy)
{
DeviceName = String.Empty;
DeviceDriver = String.Empty;
InputName = String.Empty;
Channel = 0;
}
}
interface IRecord
{
bool Init();
void CloseAll();
bool Start(SRecordDevice[] DeviceConfig);
bool Stop();
void AnalyzeBuffer(int Player);
int GetToneAbs(int Player);
int GetTone(int Player);
void SetTone(int Player, int Tone);
float GetMaxVolume(int Player);
bool ToneValid(int Player);
SRecordDevice[] RecordDevices();
}
}
+539
View File
@@ -0,0 +1,539 @@
/*
* PortAudioSharp - PortAudio bindings for .NET
* Copyright 2006-2011 Riccardo Gerosa and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Runtime.InteropServices;
namespace PortAudioSharp {
/**
<summary>
PortAudio v.19 bindings for .NET
</summary>
*/
public partial class PortAudio
{
#region **** PORTAUDIO CALLBACKS ****
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate PaStreamCallbackResult PaStreamCallbackDelegate(
IntPtr input,
IntPtr output,
uint frameCount,
ref PaStreamCallbackTimeInfo timeInfo,
PaStreamCallbackFlags statusFlags,
IntPtr userData);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void PaStreamFinishedCallbackDelegate(IntPtr userData);
#endregion
#region **** PORTAUDIO DATA STRUCTURES ****
[StructLayout (LayoutKind.Sequential)]
public struct PaDeviceInfo {
public int structVersion;
[MarshalAs (UnmanagedType.LPStr)]
public string name;
public int hostApi;
public int maxInputChannels;
public int maxOutputChannels;
public double defaultLowInputLatency;
public double defaultLowOutputLatency;
public double defaultHighInputLatency;
public double defaultHighOutputLatency;
public double defaultSampleRate;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "name: " + name + "\n"
+ "hostApi: " + hostApi + "\n"
+ "maxInputChannels: " + maxInputChannels + "\n"
+ "maxOutputChannels: " + maxOutputChannels + "\n"
+ "defaultLowInputLatency: " + defaultLowInputLatency + "\n"
+ "defaultLowOutputLatency: " + defaultLowOutputLatency + "\n"
+ "defaultHighInputLatency: " + defaultHighInputLatency + "\n"
+ "defaultHighOutputLatency: " + defaultHighOutputLatency + "\n"
+ "defaultSampleRate: " + defaultSampleRate;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaHostApiInfo {
public int structVersion;
public PaHostApiTypeId type;
[MarshalAs (UnmanagedType.LPStr)]
public string name;
public int deviceCount;
public int defaultInputDevice;
public int defaultOutputDevice;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "structVersion: " + structVersion + "\n"
+ "type: " + type + "\n"
+ "name: " + name + "\n"
+ "deviceCount: " + deviceCount + "\n"
+ "defaultInputDevice: " + defaultInputDevice + "\n"
+ "defaultOutputDevice: " + defaultOutputDevice;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaHostErrorInfo {
public PaHostApiTypeId hostApiType;
public int errorCode;
[MarshalAs (UnmanagedType.LPStr)]
public string errorText;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "hostApiType: " + hostApiType + "\n"
+ "errorCode: " + errorCode + "\n"
+ "errorText: " + errorText;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaStreamCallbackTimeInfo {
public double inputBufferAdcTime;
public double currentTime;
public double outputBufferDacTime;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "currentTime: " + currentTime + "\n"
+ "inputBufferAdcTime: " + inputBufferAdcTime + "\n"
+ "outputBufferDacTime: " + outputBufferDacTime;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaStreamInfo {
public int structVersion;
public double inputLatency;
public double outputLatency;
public double sampleRate;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "structVersion: " + structVersion + "\n"
+ "inputLatency: " + inputLatency + "\n"
+ "outputLatency: " + outputLatency + "\n"
+ "sampleRate: " + sampleRate;
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PaStreamParameters {
public int device;
public int channelCount;
public PaSampleFormat sampleFormat;
public double suggestedLatency;
public IntPtr hostApiSpecificStreamInfo;
public override string ToString() {
return "[" + this.GetType().Name + "]" + "\n"
+ "device: " + device + "\n"
+ "channelCount: " + channelCount + "\n"
+ "sampleFormat: " + sampleFormat + "\n"
+ "suggestedLatency: " + suggestedLatency;
}
}
#endregion
#region **** PORTAUDIO DEFINES ****
public enum PaDeviceIndex: int
{
paNoDevice = -1,
paUseHostApiSpecificDeviceSpecification = -2
}
public enum PaSampleFormat: uint
{
paFloat32 = 0x00000001,
paInt32 = 0x00000002,
paInt24 = 0x00000004,
paInt16 = 0x00000008,
paInt8 = 0x00000010,
paUInt8 = 0x00000020,
paCustomFormat = 0x00010000,
paNonInterleaved = 0x80000000,
}
public const int paFormatIsSupported = 0;
public const int paFramesPerBufferUnspecified = 0;
public enum PaStreamFlags: uint
{
paNoFlag = 0,
paClipOff = 0x00000001,
paDitherOff = 0x00000002,
paNeverDropInput = 0x00000004,
paPrimeOutputBuffersUsingStreamCallback = 0x00000008,
paPlatformSpecificFlags = 0xFFFF0000
}
public enum PaStreamCallbackFlags: uint
{
paInputUnderflow = 0x00000001,
paInputOverflow = 0x00000002,
paOutputUnderflow = 0x00000004,
paOutputOverflow = 0x00000008,
paPrimingOutput = 0x00000010
}
#endregion
#region **** PORTAUDIO ENUMERATIONS ****
public enum PaError : int {
paNoError = 0,
paNotInitialized = -10000,
paUnanticipatedHostError,
paInvalidChannelCount,
paInvalidSampleRate,
paInvalidDevice,
paInvalidFlag,
paSampleFormatNotSupported,
paBadIODeviceCombination,
paInsufficientMemory,
paBufferTooBig,
paBufferTooSmall,
paNullCallback,
paBadStreamPtr,
paTimedOut,
paInternalError,
paDeviceUnavailable,
paIncompatibleHostApiSpecificStreamInfo,
paStreamIsStopped,
paStreamIsNotStopped,
paInputOverflowed,
paOutputUnderflowed,
paHostApiNotFound,
paInvalidHostApi,
paCanNotReadFromACallbackStream,
paCanNotWriteToACallbackStream,
paCanNotReadFromAnOutputOnlyStream,
paCanNotWriteToAnInputOnlyStream,
paIncompatibleStreamHostApi,
paBadBufferPtr
}
public enum PaHostApiTypeId : uint {
paInDevelopment=0,
paDirectSound=1,
paMME=2,
paASIO=3,
paSoundManager=4,
paCoreAudio=5,
paOSS=7,
paALSA=8,
paAL=9,
paBeOS=10,
paWDMKS=11,
paJACK=12,
paWASAPI=13,
paAudioScienceHPI=14
}
public enum PaStreamCallbackResult : uint {
paContinue = 0,
paComplete = 1,
paAbort = 2
}
#endregion
#region **** PORTAUDIO FUNCTIONS ****
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetVersion();
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetVersionText")]
private static extern IntPtr IntPtr_Pa_GetVersionText();
public static string Pa_GetVersionText() {
IntPtr strptr = IntPtr_Pa_GetVersionText();
return Marshal.PtrToStringAnsi(strptr);
}
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetErrorText")]
public static extern IntPtr IntPtr_Pa_GetErrorText(PaError errorCode);
public static string Pa_GetErrorText(PaError errorCode) {
IntPtr strptr = IntPtr_Pa_GetErrorText(errorCode);
return Marshal.PtrToStringAnsi(strptr);
}
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_Initialize();
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_Terminate();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetHostApiCount();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDefaultHostApi();
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetHostApiInfo")]
public static extern IntPtr IntPtr_Pa_GetHostApiInfo(int hostApi);
public static PaHostApiInfo Pa_GetHostApiInfo(int hostApi) {
IntPtr structptr = IntPtr_Pa_GetHostApiInfo(hostApi);
return (PaHostApiInfo) Marshal.PtrToStructure(structptr, typeof(PaHostApiInfo));
}
[DllImport ("PortAudio.dll")]
public static extern int Pa_HostApiTypeIdToHostApiIndex(PaHostApiTypeId type);
[DllImport ("PortAudio.dll")]
public static extern int Pa_HostApiDeviceIndexToDeviceIndex(int hostApi, int hostApiDeviceIndex);
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetLastHostErrorInfo")]
public static extern IntPtr IntPtr_Pa_GetLastHostErrorInfo();
public static PaHostErrorInfo Pa_GetLastHostErrorInfo() {
IntPtr structptr = IntPtr_Pa_GetLastHostErrorInfo();
return (PaHostErrorInfo) Marshal.PtrToStructure(structptr, typeof(PaHostErrorInfo));
}
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDeviceCount();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDefaultInputDevice();
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetDefaultOutputDevice();
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetDeviceInfo")]
public static extern IntPtr IntPtr_Pa_GetDeviceInfo(int device);
public static PaDeviceInfo Pa_GetDeviceInfo(int device) {
IntPtr structptr = IntPtr_Pa_GetDeviceInfo(device);
return (PaDeviceInfo) Marshal.PtrToStructure(structptr, typeof(PaDeviceInfo));
}
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_IsFormatSupported(
ref PaStreamParameters inputParameters,
ref PaStreamParameters outputParameters,
double sampleRate);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_OpenStream(
out IntPtr stream,
ref PaStreamParameters inputParameters,
ref PaStreamParameters outputParameters,
double sampleRate,
uint framesPerBuffer,
PaStreamFlags streamFlags,
PaStreamCallbackDelegate streamCallback,
IntPtr userData);
[DllImport("PortAudio.dll")]
public static extern PaError Pa_OpenStream(
out IntPtr stream,
ref PaStreamParameters inputParameters,
IntPtr outputParameters,
double sampleRate,
uint framesPerBuffer,
PaStreamFlags streamFlags,
PaStreamCallbackDelegate streamCallback,
IntPtr userData);
[DllImport("PortAudio.dll")]
public static extern PaError Pa_OpenStream(
out IntPtr stream,
IntPtr inputParameters,
ref PaStreamParameters outputParameters,
double sampleRate,
uint framesPerBuffer,
PaStreamFlags streamFlags,
PaStreamCallbackDelegate streamCallback,
IntPtr userData);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_OpenDefaultStream(
out IntPtr stream,
int numInputChannels,
int numOutputChannels,
uint sampleFormat,
double sampleRate,
uint framesPerBuffer,
PaStreamCallbackDelegate streamCallback,
IntPtr userData);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_CloseStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_SetStreamFinishedCallback(
ref IntPtr stream,
[MarshalAs(UnmanagedType.FunctionPtr)]PaStreamFinishedCallbackDelegate streamFinishedCallback);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_StartStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_StopStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_AbortStream(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_IsStreamStopped(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_IsStreamActive(IntPtr stream);
[DllImport ("PortAudio.dll",EntryPoint="Pa_GetStreamInfo")]
public static extern IntPtr IntPtr_Pa_GetStreamInfo(IntPtr stream);
public static PaStreamInfo Pa_GetStreamInfo(IntPtr stream) {
IntPtr structptr = IntPtr_Pa_GetStreamInfo(stream);
return (PaStreamInfo) Marshal.PtrToStructure(structptr,typeof(PaStreamInfo));
}
[DllImport ("PortAudio.dll")]
public static extern double Pa_GetStreamTime(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern double Pa_GetStreamCpuLoad(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]float[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]byte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]sbyte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]ushort[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]short[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]uint[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_ReadStream(
IntPtr stream,
[Out]int[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]float[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]byte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]sbyte[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]ushort[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]short[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]uint[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_WriteStream(
IntPtr stream,
[In]int[] buffer,
uint frames);
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetStreamReadAvailable(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern int Pa_GetStreamWriteAvailable(IntPtr stream);
[DllImport ("PortAudio.dll")]
public static extern PaError Pa_GetSampleSize(PaSampleFormat format);
[DllImport ("PortAudio.dll")]
public static extern void Pa_Sleep(int msec);
#endregion
private PortAudio() {
// This is a static class
}
}
}
@@ -0,0 +1,113 @@
/*
* PortAudioSharp - PortAudio bindings for .NET
* Copyright 2006-2011 Riccardo Gerosa and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Runtime.InteropServices;
namespace PortAudioSharp {
/// <summary> PortAudio v.19 bindings for .NET - ASIO bindings </summary>
public partial class PortAudio
{
#region **** PORTAUDIO CALLBACKS ****
#endregion
#region **** PORTAUDIO DATA STRUCTURES ****
[StructLayout (LayoutKind.Sequential)]
public struct PaAsioStreamInfo {
public ulong size; /**< sizeof(PaAsioStreamInfo) */
public int hostApiType; /**< paASIO */
public ulong version; /**< 1 */
public ulong flags;
/// Support for opening only specific channels of an ASIO device.
/// If the paAsioUseChannelSelectors flag is set, channelSelectors is a
/// pointer to an array of integers specifying the device channels to use.
/// When used, the length of the channelSelectors array must match the
/// corresponding channelCount parameter to Pa_OpenStream() otherwise a
/// crash may result.
/// The values in the selectors array must specify channels within the
/// range of supported channels for the device or paInvalidChannelCount will
/// result.
IntPtr channelSelectors;
}
#endregion
#region **** PORTAUDIO DEFINES ****
public const int paAsioUseChannelSelectors = 0x01;
#endregion
#region **** PORTAUDIO ENUMERATIONS ****
#endregion
#region **** PORTAUDIO FUNCTIONS ****
// /// <summary> Retrieve legal latency settings for the specificed device, in samples. </summary>
// /// <param name="device"> The global index of the device about which the query is being made. </param>
// /// <param name="minLatency"> A pointer to the location which will recieve the minimum latency value. </param>
// /// <param name="maxLatency"> A pointer to the location which will recieve the maximum latency value. </param>
// /// <param name="preferredLatency"> A pointer to the location which will recieve the preferred latency value. </param>
// /// <param name="granularity"> A pointer to the location which will recieve the granularity. This value
// /// determines which values between minLatency and maxLatency are available. ie the step size,
// /// if granularity is -1 then available latency settings are powers of two. </param>
// /// See ASIOGetBufferSize in the ASIO SDK.
// PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device, long *minLatency, long *maxLatency,
// long *preferredLatency, long *granularity );
/// <summary> Display the ASIO control panel for the specified device. </summary>
/// <param name="device"> The global index of the device whose control panel is to be displayed. </param>
/// <param name="systemSpecific">On Windows, the calling application's main window handle,
/// on Macintosh this value should be zero.</param>
[DllImport ("PortAudio.dll")]
public static extern PortAudio.PaError PaAsio_ShowControlPanel(int device, IntPtr systemSpecific);
// /// <summary> Retrieve a pointer to a string containing the name of the specified input channel. </summary>
// /// The string is valid until Pa_Terminate is called.
// /// The string will be no longer than 32 characters including the null terminator.
// PaError PaAsio_GetInputChannelName(PaDeviceIndex device, int channelIndex, const char** channelName );
// /// <summary> Retrieve a pointer to a string containing the name of the specified input channel. </summary>
// /// The string is valid until Pa_Terminate is called.
// /// The string will be no longer than 32 characters including the null terminator.
// PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex, const char** channelName );
/// <summary> Set the sample rate of an open paASIO stream. </summary>
/// <param name="">stream</param> The stream to operate on.
/// <param name="sampleRate"></param> The new sample rate.
/// Note that this function may fail if the stream is alredy running and the
/// ASIO driver does not support switching the sample rate of a running stream.
/// <returns> paIncompatibleStreamHostApi if stream is not a paASIO stream. </returns>
[DllImport ("PortAudio.dll")]
public static extern PortAudio.PaError PaAsio_SetStreamSampleRate(IntPtr stream, double sampleRate);
#endregion
}
}
@@ -0,0 +1,10 @@
@author
Riccardo Gerosa (aka h3r3)
email: r.gerosa@gmail.com
site: http://www.postronic.org/h3
@author
Moreno Carullo
email: moreno.carullo@pulc.it
site: http://tweety.pulc.it/
+10
View File
@@ -0,0 +1,10 @@
PortAudioSharp - PortAudio bindings for .NET
Copyright 2006-2011 Riccardo Gerosa and individual contributors as indicated
by the @authors tag. See the copyright.txt in the distribution for a
full listing of individual contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+53
View File
@@ -0,0 +1,53 @@
PortAudioSharp - PortAudio bindings for .NET
Copyright (C) 2006-2011 Riccardo Gerosa
--------------------------------------------
About
-----
This library provides .NET bindings for the portable low-latency
audio library PortAudio v.19.
The bindings are available directly through the PortAudio class,
or you can even use and a simplified higher-lever Audio class.
This library is being developed using C# under Linux/mono and then
tested also on other platforms (Windows/.NET only since now)
for maximum portability.
There is no "unsafe" code.
Compiling
---------
Solution and project files for MonoDevelop 0.10 and
SharpDevelop 4.0 / Visual Studio 2008 are provided.
The solution contains three projects: The PortAudioSharp library
project, a simple test project called PortAudioSharpTest and a
WindowsFormsTest project used to test Windows Forms integration
(this feature is not yet complete).
Installing / Using
------------------
1) To use the PortAudioSharp bindings you must have the PortAudio v.19
library installed on your system, you can find PortAudio source code at
http://www.portaudio.com
Under Windows the PortAudio DLL must be named "PortAudio.dll", so
rename this file if necessary.
If you are using a Linux/Unix system you will have to compile and install
the "libportaudio.so" library.
2) If you are using a source distribution of PortAudioSharp you need
to compile it.
3) Copy PortAudioSharp.dll and PortAudioSharp.dll.config files to the
directory of your assembly.
4) Add a reference in your project to PortAudioSharp.dll
Known bugs
----------
This release may still contain some bugs,
it has been tested mainly under Windows and some versions of Linux (with Mono).
Should also work on Mac OS X (with Mono).
Please help us testing, debugging and improving these bindings!
@@ -0,0 +1,399 @@
using System;
using System.Runtime.InteropServices;
namespace Vocaluxe.Lib.Video.Acinerella
{
public enum TAc_stream_type : sbyte
{
/*The type of the media stream is not known. This kind of stream can not be
decoded.*/
AC_STREAM_TYPE_UNKNOWN = -1,
//This media stream is a video stream.
AC_STREAM_TYPE_VIDEO = 0,
//This media stream is an audio stream.
AC_STREAM_TYPE_AUDIO = 1
}
//Defines the type of an Acinerella media decoder.
public enum TAc_decoder_type : byte
{
//This decoder is used to decode a video stream.
AC_DECODER_TYPE_VIDEO = 0,
//This decoder is used to decode an audio stram.
AC_DECODER_TYPE_AUDIO = 1
}
//Defines the format video/image data is outputted in
public enum TAc_output_format : byte
{
AC_OUTPUT_RGB24 = 0,
AC_OUTPUT_BGR24 = 1,
AC_OUTPUT_RGBA32 = 2,
AC_OUTPUT_BGRA32 = 3
}
// Contains information about the whole file/stream that has been opened. Default
// values are "" for strings and -1 for integer values.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TAc_file_info
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string title;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string author;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string copyright;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string comment;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string album;
public Int32 year;
public Int32 track;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string genre;
public Int64 duration;
public Int32 bitrate;
}
// TAc_instance represents an Acinerella instance. Each instance can open and
// decode one file at once. There can be only 26 Acinerella instances opened at
// once.
[StructLayout(LayoutKind.Sequential)]
public struct TAc_instance
{
//If true, the instance currently opened a media file
public bool opened;
//Contains the count of streams the media file has. This value is available
//after calling the ac_open function.
public Int32 stream_count;
//Set this value to change the image output format
public TAc_output_format output_format;
//Contains information about the opened stream/file
public TAc_file_info info;
}
// Contains information about an Acinerella audio stream.
[StructLayout(LayoutKind.Sequential)]
public struct TAc_audio_stream_info
{
//Samples per second. Default values are 44100 or 48000.
public Int32 samples_per_second;
//Bits per sample. Can be 8 or 16 Bit.
public Int32 bit_depth;
//Count of channels in the audio stream.
public Int32 channel_count;
}
// Contains information about an Acinerella video stream.
[StructLayout(LayoutKind.Sequential)]
public struct TAc_video_stream_info
{
//The width of one frame.
public Int32 frame_width;
//The height of one frame.
public Int32 frame_height;
//The width of one pixel. 1.07 for 4:3 format, 1,42 for the 16:9 format
public float pixel_aspect;
//Frames per second that should be played.
public double frames_per_second;
}
// Contains information about an Acinerella stream.
[StructLayout(LayoutKind.Sequential)]
public struct TAc_stream_info
{
//Contains the type of the stream.
public TAc_stream_type stream_type;
//Additional info about the stream
public TAc_audio_stream_info audio_info;
public TAc_video_stream_info video_info;
}
// Contains information about an Acinerella video/audio decoder.
[StructLayout(LayoutKind.Sequential)]
public struct TAc_decoder
{
//Pointer on the Acinerella instance
public IntPtr pAcInstance;
//Contains the type of the decoder.
public TAc_decoder_type dec_type;
//The timecode of the currently decoded picture in seconds.
public double timecode;
public double video_clock;
//Contains information about the stream the decoder is attached to.
public TAc_stream_info stream_info;
//The index of the stream the decoder is attached to.
public Int32 stream_index;
//Pointer to the buffer which contains the data.
public IntPtr buffer;
//Size of the data in the buffer.
public Int32 buffer_size;
}
// Contains information about an Acinerella package.
[StructLayout(LayoutKind.Sequential)]
public struct TAc_package
{
//The stream the package belongs to.
public Int32 stream_index;
}
// Callback function used to ask the application to read data. Should return
// the number of bytes read or an value smaller than zero if an error occured.
//TAc_read_callback = function(sender: Pointer; byte[] buf, int size): integer; cdecl;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate Int32 TAc_read_callback(
IntPtr sender,
IntPtr buf,
Int32 size
);
// Callback function used to ask the application to seek. return 0 if succeed , -1 on failure.
//TAc_seek_callback = function(sender: Pointer; pos: int64; whence: integer): int64; cdecl;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate Int64 TAc_seek_callback(IntPtr sender, Int64 pos, Int32 whence);
// Callback function that is used to notify the application when the data stream
// is opened or closed. For example the file pointer should be resetted to zero
// when the "open" function is called.
// TAc_openclose_callback = function(sender: Pointer): integer; cdecl;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate Int32 TAc_openclose_callback(IntPtr sender);
public static class CAcinerella
{
private const string AcDll = "acinerella.dll";
private static Object _lock = new Object();
// Defines the type of an Acinerella media stream. Currently only video and
// audio streams are supported, subtitle and data streams will be marked as
// "unknown".
// Initializes an Acinerella instance.
//function ac_init(): PAc_instance; cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_init", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern IntPtr _ac_init();
public static IntPtr ac_init()
{
lock (_lock)
{
return _ac_init();
}
}
// Frees an Acinerella instance.
//procedure ac_free(inst: PAc_instance); cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_free", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern void _ac_free(IntPtr PAc_instance);
public static void ac_free(IntPtr PAc_instance)
{
lock (_lock)
{
_ac_free(PAc_instance);
}
}
// Opens a media file.
// @param(inst specifies the Acinerella Instance the stream should be opened for)
// @param(sender specifies a pointer that is sent to all callback functions to
// allow you to do object orientated programming. May be NULL.)
// @param(open_proc specifies the callback function that is called, when the
// media file is opened. May be NULL.)
// @param(close_proc specifies the callback function that is called when the media
// file is closed. May be NULL.)
/*function ac_open(
inst: PAc_instance;
sender: Pointer;
open_proc: TAc_openclose_callback;
read_proc: TAc_read_callback;
seek_proc: TAc_seek_callback;
close_proc: TAc_openclose_callback;
proberesult: PAc_proberesult): integer; cdecl; external ac_dll;
*/
[DllImport(AcDll, EntryPoint = "ac_open", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern Int32 _ac_open(
IntPtr PAc_instance,
IntPtr sender,
TAc_openclose_callback open_proc,
TAc_read_callback read_proc,
TAc_seek_callback seek_proc,
TAc_openclose_callback close_proc,
IntPtr proberesult
);
public static Int32 ac_open(
IntPtr PAc_instance,
IntPtr sender,
TAc_openclose_callback open_proc,
TAc_read_callback read_proc,
TAc_seek_callback seek_proc,
TAc_openclose_callback close_proc,
IntPtr proberesult
)
{
lock (_lock)
{
return _ac_open(PAc_instance, sender, open_proc, read_proc, seek_proc, close_proc, proberesult);
}
}
// Closes an opened media file.
//procedure ac_close(inst: PAc_instance);cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_close", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern void _ac_close(IntPtr PAc_instance);
public static void ac_close(IntPtr PAc_instance)
{
lock (_lock)
{
_ac_close(PAc_instance);
}
}
// Stores information in "pInfo" about stream number "nb".
//procedure ac_get_stream_info(
//inst: PAc_instance; nb: integer; pinfo: PAc_stream_info); cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_get_stream_info", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern void _ac_get_stream_info(
IntPtr PAc_instance,
Int32 nb,
out TAc_stream_info Info
);
public static void ac_get_stream_info(
IntPtr PAc_instance,
Int32 nb,
out TAc_stream_info Info
)
{
lock (_lock)
{
_ac_get_stream_info(
PAc_instance,
nb,
out Info
);
}
}
// Reads a package from an opened media file.
//function ac_read_package(inst: PAc_instance): PAc_package; cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_read_package", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern IntPtr ac_read_package(IntPtr inst);
// Frees a package that has been read.
//procedure ac_free_package(package: PAc_package); cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_free_package", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern void ac_free_package(IntPtr PAc_package);
// Creates an decoder for the specified stream number. Returns NIL if no decoder
// could be found.
//function ac_create_decoder(pacInstance: PAc_instance; nb: integer): PAc_decoder; cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_create_decoder", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern IntPtr _ac_create_decoder(IntPtr PAc_instance, Int32 nb);
public static IntPtr ac_create_decoder(IntPtr PAc_instance, Int32 nb)
{
lock (_lock)
{
return _ac_create_decoder(PAc_instance, nb);
}
}
// Frees an created decoder.
//procedure ac_free_decoder(pDecoder: PAc_decoder); cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_free_decoder", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern void _ac_free_decoder(IntPtr PAc_decoder);
public static void ac_free_decoder(IntPtr PAc_decoder)
{
lock (_lock)
{
_ac_free_decoder(PAc_decoder);
}
}
// Decodes a package using the specified decoder. The decodec data is stored in the
// "buffer" property of the decoder.
//function ac_decode_package(pPackage: PAc_package; pDecoder: PAc_decoder): integer; cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_decode_package", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern Int32 _ac_decode_package(IntPtr PAc_package, IntPtr PAc_decoder);
public static Int32 ac_decode_package(IntPtr PAc_package, IntPtr PAc_decoder)
{
lock (_lock)
{
return _ac_decode_package(PAc_package, PAc_decoder);
}
}
[DllImport(AcDll, EntryPoint = "ac_get_audio_frame", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern Int32 _ac_get_audio_frame(IntPtr PAcInstance, IntPtr PAc_decoder);
public static Int32 ac_get_audio_frame(IntPtr PAcInstance, IntPtr PAc_decoder)
{
lock (_lock)
{
return _ac_get_audio_frame(PAcInstance, PAc_decoder);
}
}
[DllImport(AcDll, EntryPoint = "ac_get_frame", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern Int32 _ac_get_frame(IntPtr PAcInstance, IntPtr PAc_decoder);
public static Int32 ac_get_frame(IntPtr PAcInstance, IntPtr PAc_decoder)
{
lock (_lock)
{
return _ac_get_frame(PAcInstance, PAc_decoder);
}
}
[DllImport(AcDll, EntryPoint = "ac_skip_frames", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern Int32 _ac_skip_frames(IntPtr PAcInstance, IntPtr PAc_decoder, Int32 num);
public static Int32 ac_skip_frames(IntPtr PAcInstance, IntPtr PAc_decoder, Int32 num)
{
lock (_lock)
{
return _ac_skip_frames(PAcInstance, PAc_decoder, num);
}
}
// Seeks to the given target position in the file. The seek funtion is not able to seek a single audio/video stream
// but seeks the whole file forward. The deocder parameter is only used as an timecode reference.
// The parameter "dir" specifies the seek direction: 0 for forward, -1 for backward.
// The target_pos paremeter is in milliseconds. Returns 1 if the functions succeded.}
//function ac_seek(pDecoder: PAc_decoder; dir: integer; target_pos: int64): integer; cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_seek", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern Int32 _ac_seek(IntPtr PAc_decoder, Int32 dir, Int64 target_pos);
public static Int32 ac_seek(IntPtr PAc_decoder, Int32 dir, Int64 target_pos)
{
lock (_lock)
{
return _ac_seek(PAc_decoder, dir, target_pos);
}
}
//function ac_probe_input_buffer(buf: PChar; bufsize: Integer; filename: PChar;
//var score_max: Integer): PAc_proberesult; cdecl; external ac_dll;
[DllImport(AcDll, EntryPoint = "ac_probe_input_buffer", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
public static extern IntPtr ac_probe_input_buffer(
IntPtr buf,
Int32 bufsize,
IntPtr filename,
out Int32 score_max
);
}
}
File diff suppressed because it is too large. Load diff
+254
View File
@@ -0,0 +1,254 @@
/*
This file is part of Acinerella.
Acinerella 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.
Acinerella 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 Acinerella. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef VIDEOPLAY_H
#define VIDEOPLAY_H
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#ifdef _WIN32
#define CALL_CONVT __cdecl
#else
#define CALL_CONVT
#endif
typedef long long int64;
/*Defines the type of an Acinerella media stream. Currently only video and
audio streams are supported, subtitle and data streams will be marked as
"unknown".*/
enum _ac_stream_type {
/*The type of the media stream is not known. This kind of stream can not be
decoded.*/
AC_STREAM_TYPE_VIDEO = 0,
/*This media stream is a video stream.*/
AC_STREAM_TYPE_AUDIO = 1,
/*This media stream is an audio stream.*/
AC_STREAM_TYPE_UNKNOWN = -1
};
typedef enum _ac_stream_type ac_stream_type;
/*Defines the type of an Acinerella media decoder.*/
enum _ac_decoder_type {
/*This decoder is used to decode a video stream.*/
AC_DECODER_TYPE_VIDEO = 0,
/* This decoder is used to decode an audio stram.*/
AC_DECODER_TYPE_AUDIO = 1
};
typedef enum _ac_decoder_type ac_decoder_type;
/*Defines the format video/image data is outputted in*/
enum _ac_output_format {
AC_OUTPUT_RGB24 = 0,
AC_OUTPUT_BGR24 = 1,
AC_OUTPUT_RGBA32 = 2,
AC_OUTPUT_BGRA32 = 3
};
typedef enum _ac_output_format ac_output_format;
/*Contains information about the whole file/stream that has been opened. Default values are ""
for strings and -1 for integer values.*/
struct _ac_file_info {
/*Information about the file*/
char title[512];
char author[512];
char copyright[512];
char comment[512];
char album[512];
int year;
int track;
char genre[32];
/*Length of the file*/
int64_t duration;
/*Bitrate*/
int bitrate;
};
typedef struct _ac_file_info ac_file_info;
typedef ac_file_info* lp_ac_file_info;
/*TAc_instance represents an Acinerella instance. Each instance can open and
decode one file at once. There can be only 26 Acinerella instances opened at
once.*/
struct _ac_instance {
/*If true, the instance currently opened a media file.*/
bool opened;
/*Contains the count of streams the media file has. This value is available
after calling the ac_open function.*/
int stream_count;
/*Set this value to change the image output format */
ac_output_format output_format;
/*Contains information about the opened stream/file*/
ac_file_info info;
};
typedef struct _ac_instance ac_instance;
/*Pointer on the Acinerella instance record.*/
typedef ac_instance* lp_ac_instance;
/*Contains information about an Acinerella video stream.*/
struct _ac_video_stream_info {
/*The width of one frame.*/
int frame_width;
/*The height of one frame.*/
int frame_height;
/*The width of one pixel. 1.07 for 4:3 format, 1,42 for the 16:9 format*/
float pixel_aspect;
/*Frames per second that should be played.*/
double frames_per_second;
};
typedef struct _ac_video_stream_info ac_video_stream_info;
/*Contains information about an Acinerella audio stream.*/
struct _ac_audio_stream_info {
/*Samples per second. Default values are 44100 or 48000.*/
int samples_per_second;
/*Bits per sample. Can be 8 or 16 Bit.*/
int bit_depth;
/*Count of channels in the audio stream.*/
int channel_count;
};
typedef struct _ac_audio_stream_info ac_audio_stream_info;
/*Contains information about an Acinerella stream.*/
struct _ac_stream_info {
/*Contains the type of the stream.*/
ac_stream_type stream_type;
ac_audio_stream_info audio_info;
ac_video_stream_info video_info;
};
typedef struct _ac_stream_info ac_stream_info;
/*Pointer on TAc_stream_info*/
typedef ac_stream_info* lp_ac_stream_info;
/*Contains information about an Acinerella video/audio decoder.*/
struct _ac_decoder {
/*Pointer on the Acinerella instance*/
lp_ac_instance pacInstance;
/*Contains the type of the decoder.*/
ac_decoder_type type;
/*The timecode of the currently decoded picture in seconds */
double timecode;
double video_clock;
/*Contains information about the stream the decoder is attached to.*/
ac_stream_info stream_info;
/*The index of the stream the decoder is attached to.*/
int stream_index;
/*Pointer to the buffer which contains the data.*/
char *pBuffer;
/*Size of the data in the buffer.*/
int buffer_size;
};
typedef struct _ac_decoder ac_decoder;
/*Pointer on TAc_decoder.*/
typedef ac_decoder* lp_ac_decoder;
/*Contains information about an Acinerella package.*/
struct _ac_package {
/*The stream the package belongs to.*/
int stream_index;
};
typedef struct _ac_package ac_package;
/*Pointer on TAc_package*/
typedef ac_package* lp_ac_package;
typedef void* lp_ac_proberesult;
/*Callback function used to ask the application to read data. Should return
the number of bytes read or an value smaller than zero if an error occured.*/
typedef int CALL_CONVT (*ac_read_callback)(void *sender, char *buf, int size);
/*Callback function used to ask the application to seek. return 0 if succeed , -1 on failure.*/
typedef int64_t CALL_CONVT (*ac_seek_callback)(void *sender, int64_t pos, int whence);
/*Callback function that is used to notify the application when the data stream
is opened or closed. For example the file pointer should be resetted to zero
when the "open" function is called.*/
typedef int CALL_CONVT (*ac_openclose_callback)(void *sender);
typedef void* CALL_CONVT (*ac_malloc_callback)(size_t size);
typedef void* CALL_CONVT (*ac_realloc_callback)(void *ptr, size_t size);
typedef void CALL_CONVT (*ac_free_callback)(void *ptr);
/*Initializes an Acinerella instance.*/
extern lp_ac_instance CALL_CONVT ac_init(void);
extern void CALL_CONVT ac_free(lp_ac_instance pacInstance);
/*Opens a media file.
@param(inst specifies the Acinerella Instance the stream should be opened for)
@param(sender specifies a pointer that is sent to all callback functions to
allow you to do object orientated programming. May be NULL.)
@param(open_proc specifies the callback function that is called, when the
media file is opened. May be NULL.)
@param(seek_proc specifies the callback function that is called, when the ffmpeg decoder
wants to seek in the file. May be NULL)
@param(close_proc specifies the callback function that is called when the media
file is closed. May be NULL.)*/
extern int CALL_CONVT ac_open(
lp_ac_instance pacInstance,
void *sender,
ac_openclose_callback open_proc,
ac_read_callback read_proc,
ac_seek_callback seek_proc,
ac_openclose_callback close_proc,
lp_ac_proberesult proberesult);
/*Closes an opened media file.*/
extern void CALL_CONVT ac_close(lp_ac_instance pacInstance);
/*Stores information in "pInfo" about stream number "nb".*/
extern void CALL_CONVT ac_get_stream_info(lp_ac_instance pacInstance, int nb, lp_ac_stream_info info);
/*Reads a package from an opened media file.*/
extern lp_ac_package CALL_CONVT ac_read_package(lp_ac_instance pacInstance);
/*Frees a package that has been read.*/
extern void CALL_CONVT ac_free_package(lp_ac_package pPackage);
/*Creates an decoder for the specified stream number. Returns NIL if no decoder
could be found.*/
extern lp_ac_decoder CALL_CONVT ac_create_decoder(lp_ac_instance pacInstance, int nb);
/*Frees an created decoder.*/
extern void CALL_CONVT ac_free_decoder(lp_ac_decoder pDecoder);
/*Decodes a package using the specified decoder. The decodec data is stored in the
"buffer" property of the decoder.*/
extern int CALL_CONVT ac_decode_package(lp_ac_package pPackage, lp_ac_decoder pDecoder);
extern int CALL_CONVT ac_drop_decode_package(lp_ac_package pPackage, lp_ac_decoder pDecoder);
extern int CALL_CONVT ac_get_audio_frame(lp_ac_instance pacInstance, lp_ac_decoder pDecoder);
extern int CALL_CONVT ac_get_frame(lp_ac_instance pacInstance, lp_ac_decoder pDecoder);
extern int CALL_CONVT ac_skip_frames(lp_ac_instance pacInstance, lp_ac_decoder pDecoder, int num);
/*Seeks to the given target position in the file. The seek funtion is not able to seek a single audio/video stream
but seeks the whole file forward. The stream number paremter (nb) is only used for the timecode reference.
The parameter "dir" specifies the seek direction: 0 for forward, -1 for backward.
The target_pos paremeter is in milliseconds. Returns 1 if the functions succeded.*/
extern int CALL_CONVT ac_seek(lp_ac_decoder pDecoder, int dir, int64_t target_pos);
extern lp_ac_proberesult CALL_CONVT ac_probe_input_buffer(void* buf, int bufsize, char* filename, int* score_max);
#endif /*VIDEOPLAY_H*/
+13
View File
@@ -0,0 +1,13 @@
acinerella: acinerella.c acinerella.h
gcc -c acinerella.c -I /usr/local/include
ifeq "$(OSTYPE)" "linux"
gcc -shared -o libacinerella.so acinerella.o -lavformat -lavcodec -lavutil -lm -lswscale
strip libacinerella.so
else
gcc -shared -o acinerella.dll -fPIC acinerella.o -lavformat -lavcodec -lavutil -lm -lswscale -lws2_32
strip acinerella.dll
endif
test: test.c acinerella.h
gcc -o test test.c -L. -lacinerella
+93
View File
@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Lib.Video
{
abstract class CVideoDecoder : IVideoDecoder
{
protected List<VideoStreams> _Streams = new List<VideoStreams>();
protected bool _Initialized = false;
public virtual bool Init()
{
_Streams = new List<VideoStreams>();
_Initialized = true;
return true;
}
public abstract void CloseAll();
public virtual int GetNumStreams()
{
return _Streams.Count;
}
public virtual int Load(string VideoFileName)
{
return 0;
}
public virtual bool Close(int StreamID)
{
return true;
}
public virtual float GetLength(int StreamID)
{
return 0f;
}
public virtual bool GetFrame(int StreamID, ref STexture Frame, float Time, ref float VideoTime)
{
return true;
}
public virtual bool Skip(int StreamID, float Start, float Gap)
{
return true;
}
public virtual void SetLoop(int StreamID, bool Loop)
{
}
public virtual void Pause(int StreamID)
{
}
public virtual void Resume(int StreamID)
{
}
public virtual bool Finished(int StreamID)
{
return false;
}
protected bool AlreadyAdded(int StreamID)
{
foreach (VideoStreams st in _Streams)
{
if (st.handle == StreamID)
{
return true;
}
}
return false;
}
protected int GetStreamIndex(int StreamID)
{
for (int i = 0; i < _Streams.Count; i++)
{
if (_Streams[i].handle == StreamID)
return i;
}
return -1;
}
}
}
+785
View File
@@ -0,0 +1,785 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Video.Acinerella;
namespace Vocaluxe.Lib.Video
{
delegate void CLOSEPROC(int StreamID);
class CVideoDecoderFFmpeg : CVideoDecoder
{
private List<Decoder> _Decoder = new List<Decoder>();
private CLOSEPROC closeproc;
private int _Count = 1;
private Object MutexDecoder = new Object();
public override bool Init()
{
closeproc = new CLOSEPROC(close_proc);
CloseAll();
return base.Init();
}
public override void CloseAll()
{
lock (MutexDecoder)
{
for (int i = 0; i < _Decoder.Count; i++)
{
_Decoder[i].Free(closeproc, i+1);
}
}
}
public override int Load(string VideoFileName)
{
VideoStreams stream = new VideoStreams(0);
Decoder decoder = new Decoder();
if (decoder.Open(VideoFileName))
{
lock (MutexDecoder)
{
_Decoder.Add(decoder);
stream.handle = _Count++;
stream.file = VideoFileName;
_Streams.Add(stream);
return stream.handle;
}
}
return -1;
}
public override bool Close(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
_Decoder[GetStreamIndex(StreamID)].Free(closeproc, StreamID);
return true;
}
}
}
return false;
}
public override bool GetFrame(int StreamID, ref STexture Frame, float Time, ref float VideoTime)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
return _Decoder[GetStreamIndex(StreamID)].GetFrame(ref Frame, Time, ref VideoTime);
}
}
}
return false;
}
public override float GetLength(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
return _Decoder[GetStreamIndex(StreamID)].Length;
}
}
}
return 0f;
}
public override bool Skip(int StreamID, float Start, float Gap)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
return _Decoder[GetStreamIndex(StreamID)].Skip(Start, Gap);
}
}
}
return false;
}
public override void SetLoop(int StreamID, bool Loop)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
_Decoder[GetStreamIndex(StreamID)].Loop = Loop;
}
}
}
}
public override void Pause(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
_Decoder[GetStreamIndex(StreamID)].Paused = true;
}
}
}
}
public override void Resume(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
_Decoder[GetStreamIndex(StreamID)].Paused = false;
}
}
}
}
public override bool Finished(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
return _Decoder[GetStreamIndex(StreamID)].Finished;
}
}
}
return true;
}
private void close_proc(int StreamID)
{
if (_Initialized)
{
lock (MutexDecoder)
{
if (AlreadyAdded(StreamID))
{
int Index = GetStreamIndex(StreamID);
_Decoder.RemoveAt(Index);
_Streams.RemoveAt(Index);
}
}
}
}
}
struct SFrameBuffer
{
public byte[] data;
public float time;
public bool displayed;
}
class Decoder
{
private IntPtr _instance = IntPtr.Zero;
private IntPtr _videodecoder = IntPtr.Zero;
private IntPtr _package = IntPtr.Zero;
private Stopwatch _Timer = new Stopwatch();
private CLOSEPROC _Closeproc;
private int _StreamID;
private string _FileName;
private FileStream _fs;
private TAc_read_callback _rc;
private TAc_seek_callback _sc;
private bool _FileOpened = false;
private float _VideoTimeBase = 0f;
private float _VideoTime = 0f;
private float _ActualVideoTime = 0f;
private bool _waiting = false;
private bool _skip = false;
private float _Time = 0f;
private float _Gap = 0f;
private float _Start = 0f;
private bool _Loop = false;
private float _Duration = 0f;
private float _VideoSkipTime = 0f;
private float _NegativeSkipTime = 0f;
private float _SkipTime = 0f;
private bool _Paused = false;
private bool _NoMoreFrames = false;
private bool _Finished = false;
private int _Width = 0;
private int _Height = 0;
private float _SetTime = 0f;
private float _SetGap = 0f;
private float _SetStart = 0f;
private bool _SetLoop = false;
private bool _SetSkip = false;
private bool _terminated = false;
private Thread _thread;
AutoResetEvent EventDecode = new AutoResetEvent(false);
SFrameBuffer[] _FrameBuffer = new SFrameBuffer[5];
Object MutexFramebuffer = new Object();
Object MutexFrame = new Object();
Object MutexSyncSignals = new Object();
public Decoder()
{
_rc = new TAc_read_callback(read_proc);
_sc = new TAc_seek_callback(seek_proc);
_thread = new Thread(Execute);
}
public void Free(CLOSEPROC close_proc, int StreamID)
{
_Closeproc = close_proc;
_StreamID = StreamID;
_terminated = true;
}
public float Length
{
get
{
if (_FileOpened)
return _Duration;
return 0f;
}
}
public bool Paused
{
get { return _Paused; }
set
{
_Paused = value;
lock (MutexSyncSignals)
{
if (_Paused)
_Timer.Stop();
else
{
_Timer.Start();
EventDecode.Set();
}
}
}
}
public bool Loop
{
get { return _SetLoop; }
set { _SetLoop = value; }
}
public bool Finished
{
get { return _Finished; }
}
public bool Open(string FileName)
{
if (_FileOpened)
return false;
if (!System.IO.File.Exists(FileName))
return false;
_FileName = FileName;
_thread.Priority = ThreadPriority.Highest;
_thread.Name = Path.GetFileName(FileName);
_thread.Start();
return true;
}
public bool GetFrame(ref STexture frame, float Time, ref float VideoTime)
{
if (!_FileOpened)
return false;
if (_Paused)
return false;
if (_SetLoop)
{
lock (MutexSyncSignals)
{
_SetTime += _Timer.ElapsedMilliseconds / 1000f;
VideoTime = _SetTime;
_Timer.Stop();
_Timer.Reset();
_Timer.Start();
}
UploadNewFrame(ref frame);
EventDecode.Set();
return true;
}
if (_Time - _SetTime >= 0 || _SetTime > Time)
{
lock (MutexSyncSignals)
{
_SetTime = Time;
VideoTime = _VideoTime;
}
UploadNewFrame(ref frame);
EventDecode.Set();
return true;
}
return false;
}
public bool Skip(float Start, float Gap)
{
lock (MutexSyncSignals)
{
_SetStart = Start;
_SetGap = Gap;
_SetSkip = true;
_NoMoreFrames = false;
_Finished = false;
}
EventDecode.Set();
return true;
}
#region Threading
private void DoSkip()
{
lock (MutexSyncSignals)
{
_VideoSkipTime = _Gap;
_NegativeSkipTime = _Start + _Gap;
_SkipTime = _Start + _Gap;
}
if (_SkipTime > 0)
{
_VideoTime = _SkipTime;
try
{
CAcinerella.ac_seek(_videodecoder, -1, (Int64)(_SkipTime * 1000f));
}
catch (Exception)
{
;
}
}
else
{
_VideoTime = 0f;
try
{
CAcinerella.ac_seek(_videodecoder, -1, (Int64)0);
}
catch (Exception)
{
;
}
}
_ActualVideoTime = _VideoTime;
lock (MutexFramebuffer)
{
for (int i = 0; i < _FrameBuffer.Length; i++)
{
_FrameBuffer[i].displayed = true;
_FrameBuffer[i].time = -1f;
}
}
_waiting = false;
}
private void Execute()
{
DoOpen();
while (!_terminated)
{
if (EventDecode.WaitOne(1) || !_waiting)
{
if (_skip)
{
DoSkip();
_skip = false;
}
if (!_waiting)
{
DoDecode();
}
if (_waiting)
Copy();
}
if (!_terminated)
{
lock (MutexSyncSignals)
{
_Time = _SetTime;
if (_SetSkip)
_skip = true;
_SetSkip = false;
_Gap = _SetGap;
_Start = _SetStart;
_Loop = _SetLoop;
}
}
}
DoFree();
}
private void DoOpen()
{
bool ok = false;
TAc_instance Instance = new TAc_instance();
try
{
_fs = new FileStream(_FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
_instance = CAcinerella.ac_init();
CAcinerella.ac_open(_instance, IntPtr.Zero, null, _rc, _sc, null, IntPtr.Zero);
Instance = (TAc_instance)Marshal.PtrToStructure(_instance, typeof(TAc_instance));
ok = true;
}
catch (Exception)
{
CLog.LogError("Error opening video file: " + _FileName);
ok = false;
}
if (!Instance.opened || !ok)
{
//Free();
return;
}
_Duration = (float)Instance.info.duration / 1000f;
int VideoStreamIndex = -1;
TAc_stream_info Info = new TAc_stream_info();
for (int i = 0; i < Instance.stream_count; i++)
{
CAcinerella.ac_get_stream_info(_instance, i, out Info);
if (Info.stream_type == TAc_stream_type.AC_STREAM_TYPE_VIDEO)
{
_videodecoder = CAcinerella.ac_create_decoder(_instance, i);
VideoStreamIndex = i;
break;
}
}
if (VideoStreamIndex < 0)
{
//Free();
return;
}
TAc_decoder Videodecoder = (TAc_decoder)Marshal.PtrToStructure(_videodecoder, typeof(TAc_decoder));
_Width = Videodecoder.stream_info.video_info.frame_width;
_Height = Videodecoder.stream_info.video_info.frame_height;
if (Videodecoder.stream_info.video_info.frames_per_second > 0)
_VideoTimeBase = 1f / (float)Videodecoder.stream_info.video_info.frames_per_second;
_VideoTime = 0f;
_Time = 0f;
for (int i = 0; i < _FrameBuffer.Length; i++)
{
_FrameBuffer[i].time = -1f;
_FrameBuffer[i].displayed = true;
_FrameBuffer[i].data = new byte[_Width * _Height * 4];
}
_FileOpened = true;
}
private void DoDecode()
{
const int FRAMEDROPCOUNT = 4;
if (!_FileOpened)
return;
if (_Paused || _NoMoreFrames)
return;
if ((_NegativeSkipTime < 0f) && (_Time + _NegativeSkipTime >= 0f))
_NegativeSkipTime = 0f;
float myTime = _Time + _VideoSkipTime;
float TimeDifference = myTime - _VideoTime;
bool DropFrame = false;
if (TimeDifference >= (FRAMEDROPCOUNT - 1) * _VideoTimeBase)
DropFrame = true;
if (_terminated)
return;
int FrameFinished = 0;
if (DropFrame)
{
try
{
FrameFinished = CAcinerella.ac_skip_frames(_instance, _videodecoder, FRAMEDROPCOUNT - 1);
}
catch (Exception)
{
CLog.LogError("Error AcSkipFrame " + _FileName);
}
}
if (!DropFrame || FrameFinished != 0)
{
lock (MutexFrame)
{
try
{
FrameFinished = CAcinerella.ac_get_frame(_instance, _videodecoder);
}
catch (Exception)
{
CLog.LogError("Error AcGetFrame " + _FileName);
}
}
}
if (FrameFinished == 0)
{
if (_Loop)
{
bool doskip = false;
float tm = 0f;
int num = -1;
lock (MutexFramebuffer)
{
for (int i = 0; i < _FrameBuffer.Length; i++)
{
if (_FrameBuffer[i].time > tm)
{
tm = _FrameBuffer[i].time;
num = i;
}
}
if (num >= 0)
doskip = _FrameBuffer[num].displayed;
}
if (!doskip)
return;
lock (MutexSyncSignals)
{
_ActualVideoTime = 0f;
_Start = 0f;
_Gap = 0f;
_SetTime = 0f;
}
DoSkip();
}
else
{
_NoMoreFrames = true;
}
return;
}
Copy();
}
private void Copy()
{
int num = -1;
lock (MutexFramebuffer)
{
for (int i = 0; i < _FrameBuffer.Length; i++)
{
if (_FrameBuffer[i].displayed)
{
num = i;
break;
}
}
if (num == -1)
_waiting = true;
else
{
lock (MutexFrame)
{
TAc_decoder Videodecoder = (TAc_decoder)Marshal.PtrToStructure(_videodecoder, typeof(TAc_decoder));
_FrameBuffer[num].time = _VideoTime;
_VideoTime = (float)Videodecoder.timecode;
if (Videodecoder.buffer != IntPtr.Zero)
{
Marshal.Copy(Videodecoder.buffer, _FrameBuffer[num].data, 0, _Width * _Height * 4);
_FrameBuffer[num].displayed = false;
}
}
_waiting = false;
}
}
}
private void UploadNewFrame(ref STexture frame)
{
if (!_FileOpened)
return;
lock (MutexFramebuffer)
{
int num = FindFrame();
if (num >= 0)
{
if (frame.index == -1 || _Width != frame.width || _Height != frame.height)
{
CDraw.RemoveTexture(ref frame);
frame = CDraw.AddTexture(_Width, _Height, ref _FrameBuffer[num].data);
}
else
{
CDraw.UpdateTexture(ref frame, ref _FrameBuffer[num].data);
}
_ActualVideoTime = _FrameBuffer[num].time;
_Finished = false;
}
else
{
if (_NoMoreFrames)
_Finished = true;
}
}
EventDecode.Set();
}
private int FindFrame()
{
int Result = -1;
float diff = 10000000f;
for (int i = 0; i < _FrameBuffer.Length; i++)
{
float td = _SetTime + _VideoSkipTime - _FrameBuffer[i].time;
if (!_FrameBuffer[i].displayed && (td < diff) && (td > _VideoTimeBase))
{
diff = Math.Abs(_FrameBuffer[i].time - _SetTime - _VideoSkipTime);
Result = i;
}
if (td > _VideoTimeBase * 2)
_FrameBuffer[i].displayed = true;
}
if (Result != -1)
_FrameBuffer[Result].displayed = true;
return Result;
}
private void DoFree()
{
if (_package != IntPtr.Zero)
CAcinerella.ac_free_package(_package);
if (_videodecoder != IntPtr.Zero)
CAcinerella.ac_free_decoder(_videodecoder);
if (_instance != IntPtr.Zero)
CAcinerella.ac_close(_instance);
if (_instance != IntPtr.Zero)
CAcinerella.ac_free(_instance);
_Closeproc(_StreamID);
}
#endregion Threading
#region Callbacks
private Int32 read_proc(IntPtr sender, IntPtr buf, Int32 size)
{
Int32 r = 0;
byte[] bb = new byte[size];
r = _fs.Read(bb, 0, size);
Marshal.Copy(bb, 0, buf, size);
return r;
}
private Int64 seek_proc(IntPtr sender, Int64 pos, Int32 whence)
{
return (Int64)_fs.Seek((long)pos, (SeekOrigin)whence);
}
#endregion Callbacks
}
}
+39
View File
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Lib.Video
{
struct VideoStreams
{
public int handle;
public string file;
public VideoStreams(int stream)
{
handle = stream;
file = String.Empty;
}
}
interface IVideoDecoder
{
bool Init();
void CloseAll();
int Load(string VideoFileName);
bool Close(int StreamID);
int GetNumStreams();
float GetLength(int StreamID);
bool GetFrame(int StreamID, ref STexture Frame, float Time, ref float VideoTime);
bool Skip(int StreamID, float Start, float Gap);
void SetLoop(int StreamID, bool Loop);
void Pause(int StreamID);
void Resume(int StreamID);
bool Finished(int StreamID);
}
}
+221
View File
@@ -0,0 +1,221 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Menu
{
public enum EBackgroundTypes
{
None,
Color,
Texture,
Video
}
struct SThemeBackground
{
public string Name;
public EBackgroundTypes Type;
public string VideoName;
public string TextureName;
public string ColorName;
}
public class CBackground : IMenuElement
{
private SThemeBackground _Theme;
private bool _ThemeLoaded;
public SColorF Color;
#region Constructors
public CBackground()
{
_ThemeLoaded = false;
_Theme = new SThemeBackground();
Color = new SColorF(0f, 0f, 0f, 1f);
}
#endregion Constructors
#region public
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
string item = XmlPath + "/" + ElementName;
_ThemeLoaded = true;
_ThemeLoaded &= CHelper.TryGetEnumValueFromXML<EBackgroundTypes>(item + "/Type", navigator, ref _Theme.Type);
bool vid = CHelper.GetValueFromXML(item + "/Video", navigator, ref _Theme.VideoName, String.Empty);
bool tex = CHelper.GetValueFromXML(item + "/Skin", navigator, ref _Theme.TextureName, String.Empty);
_ThemeLoaded &= vid || tex || _Theme.Type == EBackgroundTypes.None;
if (CHelper.GetValueFromXML(item + "/Color", navigator, ref _Theme.ColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.ColorName, SkinIndex, ref Color);
}
else
{
bool success = true;
success &= CHelper.TryGetFloatValueFromXML(item + "/R", navigator, ref Color.R);
success &= CHelper.TryGetFloatValueFromXML(item + "/G", navigator, ref Color.G);
success &= CHelper.TryGetFloatValueFromXML(item + "/B", navigator, ref Color.B);
success &= CHelper.TryGetFloatValueFromXML(item + "/A", navigator, ref Color.A);
if (_Theme.Type != EBackgroundTypes.None)
_ThemeLoaded &= success;
}
if (_ThemeLoaded)
{
_Theme.Name = ElementName;
LoadTextures();
}
return _ThemeLoaded;
}
public bool SaveTheme(XmlWriter writer)
{
if (_ThemeLoaded)
{
writer.WriteStartElement(_Theme.Name);
writer.WriteComment("<Type>: Background type: " + CConfig.ListStrings(Enum.GetNames(typeof(EBackgroundTypes))));
writer.WriteElementString("Type", Enum.GetName(typeof(EBackgroundTypes), _Theme.Type));
writer.WriteComment("<Video>: Background video name");
writer.WriteElementString("Video", _Theme.VideoName);
writer.WriteComment("<Skin>: Background Texture name");
writer.WriteElementString("Skin", _Theme.TextureName);
writer.WriteComment("<Color>: Background color for type \"Color\" from ColorScheme (high priority)");
writer.WriteComment("or <R>, <G>, <B>, <A> (lower priority)");
if (_Theme.ColorName != String.Empty)
{
writer.WriteElementString("Color", _Theme.ColorName);
}
else
{
if (_Theme.Type != EBackgroundTypes.None)
{
writer.WriteElementString("R", Color.R.ToString("#0.00"));
writer.WriteElementString("G", Color.G.ToString("#0.00"));
writer.WriteElementString("B", Color.B.ToString("#0.00"));
writer.WriteElementString("A", Color.A.ToString("#0.00"));
}
}
writer.WriteEndElement();
return true;
}
return false;
}
public void Resume()
{
if (_Theme.Type == EBackgroundTypes.Video && _Theme.VideoName != String.Empty && CConfig.VideoBackgrounds == EOffOn.TR_CONFIG_ON)
CTheme.SkinVideoResume(_Theme.VideoName);
}
public void Pause()
{
if (_Theme.VideoName != String.Empty)
CTheme.SkinVideoPause(_Theme.VideoName);
}
public bool Draw()
{
bool ok = false;
if (_Theme.Type == EBackgroundTypes.Video && CConfig.VideoBackgrounds == EOffOn.TR_CONFIG_ON)
ok = DrawVideo();
if (_Theme.TextureName != String.Empty &&
(_Theme.Type == EBackgroundTypes.Texture ||
(_Theme.Type == EBackgroundTypes.Video && (CConfig.VideoBackgrounds == EOffOn.TR_CONFIG_OFF || !ok))))
ok = DrawTexture();
if (_Theme.Type == EBackgroundTypes.Color || _Theme.Type == EBackgroundTypes.Texture && !ok ||
(_Theme.Type == EBackgroundTypes.Video && CConfig.VideoBackgrounds == EOffOn.TR_CONFIG_OFF && !ok))
DrawColor();
return true;
}
public void UnloadTextures()
{
}
public void LoadTextures()
{
if (_Theme.ColorName != String.Empty)
Color = CTheme.GetColor(_Theme.ColorName);
}
public void ReloadTextures()
{
UnloadTextures();
LoadTextures();
}
#endregion public
#region internal
private void DrawColor()
{
SRectF bounds = new SRectF(0f, 0f, CSettings.iRenderW, CSettings.iRenderH, CSettings.zFar/4);
CDraw.DrawColor(Color, bounds);
}
private bool DrawTexture()
{
STexture Texture = CTheme.GetSkinTexture(_Theme.TextureName);
if (Texture.height > 0)
{
RectangleF bounds = new RectangleF(0f, 0f, CSettings.iRenderW, CSettings.iRenderH);
RectangleF rect = new RectangleF(0f, 0f, Texture.width, Texture.height);
CHelper.SetRect(bounds, ref rect, rect.Width / rect.Height, EAspect.Crop);
CDraw.DrawTexture(Texture, new SRectF(rect.X, rect.Y, rect.Width, rect.Height, CSettings.zFar / 4));
return true;
}
return false;
}
private bool DrawVideo()
{
STexture VideoTexture = CTheme.GetSkinVideoTexture(_Theme.VideoName);
if (VideoTexture.height > 0)
{
RectangleF bounds = new RectangleF(0f, 0f, CSettings.iRenderW, CSettings.iRenderH);
RectangleF rect = new RectangleF(0f, 0f, VideoTexture.width, VideoTexture.height);
CHelper.SetRect(bounds, ref rect, rect.Width / rect.Height, EAspect.Crop);
CDraw.DrawTexture(VideoTexture, new SRectF(rect.X, rect.Y, rect.Width, rect.Height, CSettings.zFar / 4));
return true;
}
return false;
}
#endregion internal
#region ThemeEdit
public void MoveElement(int stepX, int stepY)
{
}
public void ResizeElement(int stepW, int stepH)
{
}
#endregion ThemeEdit
}
}
+304
View File
@@ -0,0 +1,304 @@
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Menu
{
struct SThemeButton
{
public string Name;
public string ColorName;
public string SColorName;
public string TextureName;
public string STextureName;
}
class CButton : IMenuElement
{
private SThemeButton _Theme;
private bool _ThemeLoaded;
public SRectF Rect;
public SColorF Color;
public SColorF SColor;
public CText Text;
public bool Reflection;
public float ReflectionSpace;
public float ReflectionHeight;
public bool SReflection;
public float SReflectionSpace;
public float SReflectionHeight;
private bool _Selected;
public bool Selected
{
get { return _Selected; }
set
{
_Selected = value;
Text.Selected = value;
}
}
public bool Visible;
public CButton()
{
_Theme = new SThemeButton();
Rect = new SRectF();
Color = new SColorF();
SColor = new SColorF();
Text = new CText();
Selected = false;
Visible = true;
Reflection = false;
ReflectionSpace = 0f;
ReflectionHeight = 0f;
SReflection = false;
SReflectionSpace = 0f;
SReflectionHeight = 0f;
}
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
string item = XmlPath + "/" + ElementName;
_ThemeLoaded = true;
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/Skin", navigator, ref _Theme.TextureName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinSelected", navigator, ref _Theme.STextureName, String.Empty);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/X", navigator, ref Rect.X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Y", navigator, ref Rect.Y);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Z", navigator, ref Rect.Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/W", navigator, ref Rect.W);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/H", navigator, ref Rect.H);
if (CHelper.GetValueFromXML(item + "/Color", navigator, ref _Theme.ColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.ColorName, SkinIndex, ref Color);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/R", navigator, ref Color.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/G", navigator, ref Color.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/B", navigator, ref Color.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/A", navigator, ref Color.A);
}
if (CHelper.GetValueFromXML(item + "/SColor", navigator, ref _Theme.SColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.SColorName, SkinIndex, ref SColor);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SR", navigator, ref SColor.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SG", navigator, ref SColor.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SB", navigator, ref SColor.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SA", navigator, ref SColor.A);
}
_ThemeLoaded &= Text.LoadTheme(item, "Text", navigator, SkinIndex, true);
Text.Z = Rect.Z;
//Reflections
if (CHelper.ItemExistsInXML(item + "/Reflection", navigator))
{
Reflection = true;
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Reflection/Space", navigator, ref ReflectionSpace);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Reflection/Height", navigator, ref ReflectionHeight);
}
else
Reflection = false;
if (CHelper.ItemExistsInXML(item + "/SReflection", navigator))
{
SReflection = true;
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SReflection/Space", navigator, ref SReflectionSpace);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SReflection/Height", navigator, ref SReflectionHeight);
}
else
SReflection = false;
if (_ThemeLoaded)
{
_Theme.Name = ElementName;
LoadTextures();
}
return _ThemeLoaded;
}
public bool SaveTheme(XmlWriter writer)
{
if (_ThemeLoaded)
{
writer.WriteStartElement(_Theme.Name);
writer.WriteComment("<Skin>: Texture name");
writer.WriteElementString("Skin", _Theme.TextureName);
writer.WriteComment("<SkinSelected>: Texture name for selected button");
writer.WriteElementString("SkinSelected", _Theme.STextureName);
writer.WriteComment("<X>, <Y>, <Z>, <W>, <H>: Button position, width and height");
writer.WriteElementString("X", Rect.X.ToString("#0"));
writer.WriteElementString("Y", Rect.Y.ToString("#0"));
writer.WriteElementString("Z", Rect.Z.ToString("#0.00"));
writer.WriteElementString("W", Rect.W.ToString("#0"));
writer.WriteElementString("H", Rect.H.ToString("#0"));
writer.WriteComment("<Color>: Button color from ColorScheme (high priority)");
writer.WriteComment("or <R>, <G>, <B>, <A> (lower priority)");
if (_Theme.ColorName != String.Empty)
{
writer.WriteElementString("Color", _Theme.ColorName);
}
else
{
writer.WriteElementString("R", Color.R.ToString("#0.00"));
writer.WriteElementString("G", Color.G.ToString("#0.00"));
writer.WriteElementString("B", Color.B.ToString("#0.00"));
writer.WriteElementString("A", Color.A.ToString("#0.00"));
}
writer.WriteComment("<SColor>: Selected button color from ColorScheme (high priority)");
writer.WriteComment("or <SR>, <SG>, <SB>, <SA> (lower priority)");
if (_Theme.SColorName != String.Empty)
{
writer.WriteElementString("SColor", _Theme.SColorName);
}
else
{
writer.WriteElementString("SR", SColor.R.ToString("#0.00"));
writer.WriteElementString("SG", SColor.G.ToString("#0.00"));
writer.WriteElementString("SB", SColor.B.ToString("#0.00"));
writer.WriteElementString("SA", SColor.A.ToString("#0.00"));
}
Text.SaveTheme(writer);
writer.WriteComment("<Reflection> If exists:");
writer.WriteComment(" <Space>: Reflection Space");
writer.WriteComment(" <Height>: Reflection Height");
if (Reflection)
{
writer.WriteStartElement("Reflection");
writer.WriteElementString("Space", ReflectionSpace.ToString("#0"));
writer.WriteElementString("Height", ReflectionHeight.ToString("#0"));
writer.WriteEndElement();
}
writer.WriteComment("<SReflection> If exists:");
writer.WriteComment(" <Space>: Reflection Space of selected button");
writer.WriteComment(" <Height>: Reflection Height of selected button");
if (SReflection)
{
writer.WriteStartElement("SReflection");
writer.WriteElementString("Space", ReflectionSpace.ToString("#0"));
writer.WriteElementString("Height", ReflectionHeight.ToString("#0"));
writer.WriteEndElement();
}
writer.WriteEndElement();
return true;
}
return false;
}
public void Draw()
{
Draw(false);
}
public void ForceDraw()
{
Draw(true);
}
public void Draw(bool ForceDraw)
{
if (!Visible && CSettings.GameState != EGameState.EditTheme && !ForceDraw)
return;
STexture texture = new STexture(-1);
if (!Selected)
{
texture = CTheme.GetSkinTexture(_Theme.TextureName);
CDraw.DrawTexture(texture, Rect, Color);
if (Reflection)
{
CDraw.DrawTextureReflection(texture, Rect, Color, Rect, ReflectionSpace, ReflectionHeight);
}
}
else
{
texture = CTheme.GetSkinTexture(_Theme.STextureName);
CDraw.DrawTexture(texture, Rect, SColor);
if (Reflection)
{
CDraw.DrawTextureReflection(texture, Rect, SColor, Rect, ReflectionSpace, ReflectionHeight);
}
}
Text.DrawRelative(Rect.X, Rect.Y);
if (Reflection)
{
Text.DrawRelative(Rect.X, Rect.Y, ReflectionSpace, ReflectionHeight, Rect.H);
}
}
public void UnloadTextures()
{
Text.UnloadTextures();
}
public void LoadTextures()
{
Text.LoadTextures();
if (_Theme.ColorName != String.Empty)
Color = CTheme.GetColor(_Theme.ColorName);
if (_Theme.SColorName != String.Empty)
SColor = CTheme.GetColor(_Theme.SColorName);
}
public void ReloadTextures()
{
UnloadTextures();
LoadTextures();
}
#region ThemeEdit
public void MoveElement(int stepX, int stepY)
{
Rect.X += stepX;
Rect.Y += stepY;
}
public void ResizeElement(int stepW, int stepH)
{
Rect.W += stepW;
if (Rect.W <= 0)
Rect.W = 1;
Rect.H += stepH;
if (Rect.H <= 0)
Rect.H = 1;
}
#endregion ThemeEdit
}
}
+600
View File
@@ -0,0 +1,600 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Screens;
namespace Vocaluxe.Menu
{
enum EScreens
{
ScreenTest = 0,
ScreenLoad = 1,
ScreenMain = 2,
ScreenSong = 3,
ScreenOptions = 4,
ScreenSing = 5,
ScreenProfiles = 6,
ScreenScore = 7,
ScreenHighscore = 8,
ScreenOptionsGame = 9,
ScreenOptionsSound = 10,
ScreenOptionsRecord = 11,
ScreenOptionsVideo = 12,
ScreenOptionsTheme = 13,
ScreenNames = 14,
ScreenNull = -1
}
class CCursor
{
private Stopwatch _CursorFadingTimer;
private float _CursorTargetAlpha;
private float _CursorStartAlpha;
private float _CursorFadingTime;
private STexture _Cursor;
private string _CursorName = String.Empty;
private Stopwatch _Movetimer;
public bool ShowCursor;
public bool Visible = true;
public bool CursorVisible = true;
public int X
{
get { return (int)_Cursor.rect.X; }
set { UpdatePosition(value, (int)_Cursor.rect.Y); }
}
public int Y
{
get { return (int)_Cursor.rect.Y; }
set { UpdatePosition((int)_Cursor.rect.X, value); }
}
public bool IsActive
{
get { return _Movetimer.IsRunning; }
}
public CCursor(string textureName, SColorF color, float w, float h, float z)
{
_CursorFadingTimer = new Stopwatch();
ShowCursor = true;
_CursorTargetAlpha = 1f;
_CursorStartAlpha = 0f;
_CursorFadingTime = 0.5f;
_CursorName = textureName;
_Cursor = CDraw.AddTexture(CTheme.GetSkinFilePath(_CursorName));
_Cursor.color = color;
_Cursor.rect.W = w;
_Cursor.rect.H = h;
_Cursor.rect.Z = z;
_Movetimer = new Stopwatch();
}
public void Draw()
{
if (_Movetimer.IsRunning && _Movetimer.ElapsedMilliseconds / 1000f > CSettings.MouseMoveOffTime)
{
_Movetimer.Stop();
Fade(0f, 0.5f);
}
if (_CursorFadingTimer.IsRunning)
{
float t = _CursorFadingTimer.ElapsedMilliseconds / 1000f;
if (t < _CursorFadingTime)
{
if (_CursorTargetAlpha >= _CursorStartAlpha)
_Cursor.color.A = (_CursorTargetAlpha - _CursorStartAlpha) * t / _CursorFadingTime;
else
_Cursor.color.A = (_CursorStartAlpha - _CursorTargetAlpha) * (1f - t / _CursorFadingTime);
}
else
{
_CursorFadingTimer.Stop();
_Cursor.color.A = _CursorTargetAlpha;
}
}
if (CursorVisible && (CSettings.GameState == EGameState.EditTheme || ShowCursor))
CDraw.DrawTexture(_Cursor);
}
public void UpdatePosition(int x, int y)
{
if (Math.Abs(_Cursor.rect.X - x) > CSettings.MouseMoveDiffMin ||
Math.Abs(_Cursor.rect.Y - y) > CSettings.MouseMoveDiffMin)
{
if (_CursorTargetAlpha == 0f)
Fade(1f, 0.2f);
_Movetimer.Reset();
_Movetimer.Start();
CSettings.MouseActive();
}
_Cursor.rect.X = x;
_Cursor.rect.Y = y;
}
public void UnloadTextures()
{
CDraw.RemoveTexture(ref _Cursor);
}
public void ReloadTextures()
{
UnloadTextures();
_Cursor = CDraw.AddTexture(CTheme.GetSkinFilePath(_CursorName));
}
public void FadeOut()
{
_Movetimer.Stop();
Fade(0f, 0.5f);
}
private void Fade(float targetAlpha, float time)
{
_CursorFadingTimer.Stop();
_CursorFadingTimer.Reset();
if (targetAlpha >= 0f && targetAlpha <= 1f)
_CursorTargetAlpha = targetAlpha;
else
_CursorTargetAlpha = 1f;
if (time >= 0f)
_CursorFadingTime = time;
_CursorStartAlpha = _Cursor.color.A;
_CursorFadingTimer.Start();
}
}
static class CGraphics
{
private static bool _Fading = false;
private static Stopwatch _FadingTimer;
private static CCursor _Cursor;
private static float _GlobalAlpha;
private static float _ZOffset;
private static EScreens ActualScreen;
private static EScreens NextScreen;
private static List<CMenu> ScreenList = new List<CMenu>();
private static CMenu[] Screens;
public static float GlobalAlpha
{
get { return _GlobalAlpha; }
}
public static float ZOffset
{
get { return _ZOffset; }
}
#region public methods
public static void InitGraphics()
{
// Add Screens, must be the same order as in EScreens!
CLog.StartBenchmark(1, "Build Screen List");
ScreenList.Add(new CScreenTest());
ScreenList.Add(new CScreenLoad());
ScreenList.Add(new CScreenMain());
ScreenList.Add(new CScreenSong());
ScreenList.Add(new CScreenOptions());
ScreenList.Add(new CScreenSing());
ScreenList.Add(new CScreenProfiles());
ScreenList.Add(new CScreenScore());
ScreenList.Add(new CScreenHighscore());
ScreenList.Add(new CScreenOptionsGame());
ScreenList.Add(new CScreenOptionsSound());
ScreenList.Add(new CScreenOptionsRecord());
ScreenList.Add(new CScreenOptionsVideo());
ScreenList.Add(new CScreenOptionsTheme());
ScreenList.Add(new CScreenNames());
CLog.StopBenchmark(1, "Build Screen List");
Screens = ScreenList.ToArray();
ActualScreen = EScreens.ScreenLoad;
NextScreen = EScreens.ScreenNull;
_FadingTimer = new Stopwatch();
_GlobalAlpha = 1f;
_ZOffset = 0f;
CLog.StartBenchmark(0, "Load Theme");
LoadTheme();
CLog.StopBenchmark(0, "Load Theme");
}
public static void LoadTheme()
{
_Cursor = new CCursor(
CTheme.Cursor.SkinName,
new SColorF(CTheme.Cursor.r, CTheme.Cursor.g, CTheme.Cursor.b, CTheme.Cursor.a),
CTheme.Cursor.w,
CTheme.Cursor.h,
CSettings.zNear);
for (int i = 0; i < Screens.Length; i++)
{
CLog.StartBenchmark(1, "Load Theme " + Enum.GetNames(typeof(EScreens))[i]);
Screens[i].LoadTheme();
CLog.StopBenchmark(1, "Load Theme " + Enum.GetNames(typeof(EScreens))[i]);
}
}
public static void ReloadTheme()
{
ReloadCursor();
for (int i = 0; i < Screens.Length; i++)
{
Screens[i].ReloadTheme();
}
}
public static void ReloadSkin()
{
ReloadCursor();
for (int i = 0; i < Screens.Length; i++)
{
Screens[i].ReloadTextures();
}
}
public static void SaveTheme()
{
CTheme.SaveTheme();
for (int i = 0; i < Screens.Length; i++)
{
Screens[i].SaveTheme();
}
}
public static void InitFirstScreen()
{
Screens[(int)ActualScreen].OnShow();
Screens[(int)ActualScreen].OnShowFinish();
}
public static CMenu GetScreen(int Index)
{
return Screens[Index];
}
public static bool UpdateGameLogic(CKeys Keys, CMouse Mouse)
{
bool _Run = true;
_Cursor.CursorVisible = Mouse.Visible;
Mouse.CopyEvents();
Keys.CopyEvents();
CSound.Update();
if (CConfig.CoverLoading == ECoverLoading.TR_CONFIG_COVERLOADING_DYNAMIC && ActualScreen != EScreens.ScreenSing)
CSongs.LoadCover(30L);
if (CSettings.GameState != EGameState.EditTheme)
{
_Run &= HandleInputs(Keys, Mouse);
_Run &= Update();
}
else
{
_Run &= HandleInputThemeEditor(Keys, Mouse);
_Run &= Update();
}
return _Run;
}
public static bool Draw()
{
if ((NextScreen != EScreens.ScreenNull) && !_Fading)
{
_Fading = true;
_FadingTimer.Reset();
_FadingTimer.Start();
Screens[(int)NextScreen].OnShow();
}
if (_Fading)
{
long FadeTime = (long)(CConfig.FadeTime * 1000);
if ((_FadingTimer.ElapsedMilliseconds < FadeTime) && (CConfig.FadeTime > 0))
{
long ms = 1;
if (_FadingTimer.ElapsedMilliseconds > 0)
ms = _FadingTimer.ElapsedMilliseconds;
float factor = (float)ms / FadeTime;
_GlobalAlpha = 1f;// -factor / 100f;
_ZOffset = CSettings.zFar/2;
Screens[(int)ActualScreen].Draw();
_GlobalAlpha = factor;
_ZOffset = 0f;
Screens[(int)NextScreen].Draw();
_GlobalAlpha = 1f;
}
else
{
Screens[(int)ActualScreen].OnClose();
ActualScreen = NextScreen;
NextScreen = EScreens.ScreenNull;
Screens[(int)ActualScreen].OnShowFinish();
Screens[(int)ActualScreen].Draw();
_Fading = false;
_FadingTimer.Stop();
}
}
else
{
Screens[(int)ActualScreen].Draw();
}
_Cursor.Draw();
DrawDebugInfos();
return true;
}
public static void FadeTo(EScreens Screen)
{
NextScreen = Screen;
}
public static void HideCursor()
{
_Cursor.ShowCursor = false;
}
public static void ShowCursor()
{
_Cursor.ShowCursor = true;
}
#endregion public methods
#region private stuff
private static bool HandleInputs(CKeys keys, CMouse Mouse)
{
KeyEvent KeyEvent = new KeyEvent();
MouseEvent MouseEvent = new MouseEvent();
bool Resume = true;
while (keys.PollEvent(ref KeyEvent))
{
if (KeyEvent.Key == Keys.Left || KeyEvent.Key == Keys.Right || KeyEvent.Key == Keys.Up || KeyEvent.Key == Keys.Down)
{
CSettings.MouseInacive();
_Cursor.FadeOut();
}
if (KeyEvent.ModSHIFT && (KeyEvent.Key == Keys.F1))
{
CSettings.GameState = EGameState.EditTheme;
}
else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.Enter ))
{
CSettings.bFullScreen = !CSettings.bFullScreen;
}
else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.P))
{
CDraw.MakeScreenShot();
}
else
{
if (!_Fading)
Resume &= Screens[(int)ActualScreen].HandleInput(KeyEvent);
}
}
while (Mouse.PollEvent(ref MouseEvent))
{
UpdateMousePosition(MouseEvent.X, MouseEvent.Y);
if (!_Fading && (_Cursor.IsActive || MouseEvent.LB || MouseEvent.RB))
Resume &= Screens[(int)ActualScreen].HandleMouse(MouseEvent);
}
return Resume;
}
private static bool HandleInputThemeEditor(CKeys keys, CMouse Mouse)
{
KeyEvent KeyEvent = new KeyEvent();
MouseEvent MouseEvent = new MouseEvent();
while (keys.PollEvent(ref KeyEvent))
{
if (KeyEvent.ModSHIFT && (KeyEvent.Key == Keys.F1))
{
CSettings.GameState = EGameState.Normal;
Screens[(int)ActualScreen].NextInteraction();
}
else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.Enter))
{
CSettings.bFullScreen = !CSettings.bFullScreen;
}
else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.P))
{
CDraw.MakeScreenShot();
}
else
{
if (!_Fading)
Screens[(int)ActualScreen].HandleInputThemeEditor(KeyEvent);
}
}
while (Mouse.PollEvent(ref MouseEvent))
{
if (!_Fading)
Screens[(int)ActualScreen].HandleMouseThemeEditor(MouseEvent);
UpdateMousePosition(MouseEvent.X, MouseEvent.Y);
}
return true;
}
private static void UpdateMousePosition(int x, int y)
{
_Cursor.UpdatePosition(x, y);
}
private static bool Update()
{
return Screens[(int)ActualScreen].UpdateGame();
}
private static void DrawDebugInfos()
{
string txt = String.Empty;
CFonts.Style = EStyle.Normal;
CFonts.SetFont("Normal");
SColorF Gray = new SColorF(1f, 1f, 1f, 0.5f);
float dy = 0;
if (CConfig.DebugLevel >= EDebugLevel.TR_CONFIG_ONLY_FPS)
{
txt = CTime.GetFPS().ToString("FPS: 000");
CFonts.Height = 30f;
RectangleF rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
}
if (CConfig.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL1)
{
txt = CSound.GetStreamCount().ToString(CLanguage.Translate("TR_DEBUG_AUDIO_STREAMS") + ": 00");
RectangleF rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
}
if (CConfig.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL1)
{
txt = CVideo.GetNumStreams().ToString(CLanguage.Translate("TR_DEBUG_VIDEO_STREAMS") + ": 00");
RectangleF rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
}
if (CConfig.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL1)
{
txt = CDraw.TextureCount().ToString(CLanguage.Translate("TR_DEBUG_TEXTURES") + ": 00000");
RectangleF rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
}
if (CConfig.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL2)
{
txt = CSound.RecordGetToneAbs(0).ToString(CLanguage.Translate("TR_DEBUG_TONE_ABS") + " P1: 00");
RectangleF rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
txt = CSound.RecordGetMaxVolume(0).ToString(CLanguage.Translate("TR_DEBUG_MAX_VOLUME") + " P1: 0.000");
rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
txt = CSound.RecordGetToneAbs(1).ToString(CLanguage.Translate("TR_DEBUG_TONE_ABS") + " P2: 00");
rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
txt = CSound.RecordGetMaxVolume(1).ToString(CLanguage.Translate("TR_DEBUG_MAX_VOLUME") + " P2: 0.000");
rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
}
if (CConfig.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL2)
{
txt = CSongs.NumSongsWithCoverLoaded.ToString(CLanguage.Translate("TR_DEBUG_SONGS") + ": 00000");
RectangleF rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
}
if (CConfig.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL2)
{
txt = _Cursor.X.ToString(CLanguage.Translate("TR_DEBUG_MOUSE") + " : (0000/") + _Cursor.Y.ToString("0000)");
RectangleF rect = new RectangleF(CSettings.iRenderW - CFonts.GetTextWidth(txt), dy, CFonts.GetTextWidth(txt), CFonts.GetTextHeight(txt));
CDraw.DrawColor(Gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.zNear));
CFonts.DrawText(txt, rect.X, rect.Y, CSettings.zNear);
dy += rect.Height;
}
}
private static void ReloadCursor()
{
_Cursor.UnloadTextures();
_Cursor = new CCursor(
CTheme.Cursor.SkinName,
new SColorF(CTheme.Cursor.r, CTheme.Cursor.g, CTheme.Cursor.b, CTheme.Cursor.a),
CTheme.Cursor.w,
CTheme.Cursor.h,
CSettings.zNear);
}
#endregion private stuff
}
}
+53
View File
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Menu
{
public enum EType
{
TBackground,
TButton,
TSelectSlide,
TText,
TStatic,
TSongMenu,
TLyric,
TSingNote
}
class CInteraction
{
private int _Num;
private EType _Type;
public int Num
{
get { return _Num; }
}
public EType Type
{
get { return _Type; }
}
public bool ThemeEditorOnly
{
get
{
return (_Type == EType.TBackground ||
_Type == EType.TText ||
_Type == EType.TStatic ||
_Type == EType.TSongMenu ||
_Type == EType.TLyric ||
_Type == EType.TSingNote);
}
}
public CInteraction(int num, EType type)
{
_Num = num;
_Type = type;
}
}
}
+329
View File
@@ -0,0 +1,329 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Song;
namespace Vocaluxe.Menu
{
enum ELyricStyle
{
Fill,
Jump,
Slide
}
struct SNote
{
public string Text;
public int StartBeat;
public int EndBeat;
public ENoteType Type;
}
struct SThemeLyrics
{
public string Name;
public string ColorName;
public string SColorName;
}
class CLyric : IMenuElement
{
private SThemeLyrics _Theme;
private bool _ThemeLoaded;
private List<SNote> _Notes;
private CText _Text;
private float _X;
private float _Y;
private float _MaxW;
private float _Z;
private float _H;
private float _width;
private ELyricStyle _Style;
private float _Alpha = 1f;
public SRectF Rect
{
get { return new SRectF(_X, _Y, _MaxW, _H, _Z); }
set
{
_X = value.X;
_Y = value.Y;
_MaxW = value.W;
_H = value.H;
_Z = value.Z;
}
}
public SColorF Color;
public SColorF ColorProcessed;
public bool Selected;
public bool Visible = true;
public float Alpha
{
get { return _Alpha; }
set
{
_Alpha = value;
_Text.Alpha = _Alpha;
}
}
public CLyric()
{
_Theme = new SThemeLyrics();
_ThemeLoaded = false;
Color = new SColorF();
ColorProcessed = new SColorF();
_X = 0f;
_Y = 0f;
_Z = 0f;
_MaxW = 1f;
_H = 1f;
_width = 1f;
_Notes = new List<SNote>();
_Text = new CText();
_Style = ELyricStyle.Slide;
}
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
string item = XmlPath + "/" + ElementName;
_ThemeLoaded = true;
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/X", navigator, ref _X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Y", navigator, ref _Y);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Z", navigator, ref _Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/W", navigator, ref _MaxW);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/H", navigator, ref _H);
if (CHelper.GetValueFromXML(item + "/Color", navigator, ref _Theme.ColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.ColorName, SkinIndex, ref Color);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/R", navigator, ref Color.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/G", navigator, ref Color.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/B", navigator, ref Color.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/A", navigator, ref Color.A);
}
if (CHelper.GetValueFromXML(item + "/SColor", navigator, ref _Theme.SColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.SColorName, SkinIndex, ref ColorProcessed);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SR", navigator, ref ColorProcessed.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SG", navigator, ref ColorProcessed.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SB", navigator, ref ColorProcessed.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SA", navigator, ref ColorProcessed.A);
}
if (_ThemeLoaded)
{
_Theme.Name = ElementName;
LoadTextures();
_Text = new CText(_X, _Y, _Z, _H, _MaxW, EAlignment.Left, EStyle.Bold, "Normal", Color, String.Empty);
}
return _ThemeLoaded;
}
public bool SaveTheme(XmlWriter writer)
{
if (_ThemeLoaded)
{
writer.WriteStartElement(_Theme.Name);
writer.WriteComment("<X>, <Y>, <Z>, <W>, <H>: Lyric position, width and height");
writer.WriteElementString("X", _X.ToString("#0"));
writer.WriteElementString("Y", _Y.ToString("#0"));
writer.WriteElementString("Z", _Z.ToString("#0.00"));
writer.WriteElementString("W", _MaxW.ToString("#0"));
writer.WriteElementString("H", _H.ToString("#0"));
writer.WriteComment("<Color>: Lyric text color from ColorScheme (high priority)");
writer.WriteComment("or <R>, <G>, <B>, <A> (lower priority)");
if (_Theme.ColorName != String.Empty)
{
writer.WriteElementString("Color", _Theme.ColorName);
}
else
{
writer.WriteElementString("R", Color.R.ToString("#0.00"));
writer.WriteElementString("G", Color.G.ToString("#0.00"));
writer.WriteElementString("B", Color.B.ToString("#0.00"));
writer.WriteElementString("A", Color.A.ToString("#0.00"));
}
writer.WriteComment("<SColor>: Highlighted lyric color from ColorScheme (high priority)");
writer.WriteComment("or <SR>, <SG>, <SB>, <SA> (lower priority)");
if (_Theme.SColorName != String.Empty)
{
writer.WriteElementString("SColor", _Theme.SColorName);
}
else
{
writer.WriteElementString("SR", ColorProcessed.R.ToString("#0.00"));
writer.WriteElementString("SG", ColorProcessed.G.ToString("#0.00"));
writer.WriteElementString("SB", ColorProcessed.B.ToString("#0.00"));
writer.WriteElementString("SA", ColorProcessed.A.ToString("#0.00"));
}
writer.WriteEndElement();
return true;
}
return false;
}
public void SetLine(CLine Line)
{
_Notes.Clear();
_width = 0f;
foreach (CNote note in Line.Notes)
{
SNote n = new SNote();
n.Text = note.Text;
n.StartBeat = note.StartBeat;
n.EndBeat = note.EndBeat;
n.Type = note.NoteType;
_Text.Text = note.Text;
_Text.Style = EStyle.Bold;
if (n.Type == ENoteType.Freestyle)
_Text.Style = EStyle.BoldItalic;
RectangleF rect = CDraw.GetTextBounds(_Text);
_width += rect.Width;
_Notes.Add(n);
}
}
public void Clear()
{
_Notes.Clear();
}
public float GetCurrentLyricPosX()
{
return _X - _width / 2;
}
public void Draw(float ActualBeat)
{
if (Visible || CSettings.GameState == EGameState.EditTheme)
DrawSlide(ActualBeat);
}
private void DrawSlide(float CurrentBeat)
{
float x = _X - _width / 2;
foreach (SNote note in _Notes)
{
_Text.X = x;
_Text.Style = EStyle.Bold;
if (note.Type == ENoteType.Freestyle)
_Text.Style = EStyle.BoldItalic;
if (CurrentBeat >= note.StartBeat)
{
if (CurrentBeat <= note.EndBeat)
{
_Text.Color = ColorProcessed;
_Text.Text = note.Text;
float diff = note.EndBeat - note.StartBeat;
if (diff == 0)
_Text.Draw(0f, 1f);
else
{
_Text.Draw(0f, (CurrentBeat - note.StartBeat) / diff);
_Text.Color = Color;
_Text.Draw((CurrentBeat - note.StartBeat) / diff, 1f);
}
}
else
{
_Text.Color = ColorProcessed;
_Text.Text = note.Text;
_Text.Draw();
}
}
else
{
_Text.Color = Color;
_Text.Text = note.Text;
_Text.Draw();
}
RectangleF rect = CDraw.GetTextBounds(_Text);
x += rect.Width;
}
}
public void UnloadTextures()
{
}
public void LoadTextures()
{
if (_Theme.ColorName != String.Empty)
Color = CTheme.GetColor(_Theme.ColorName);
if (_Theme.SColorName != String.Empty)
ColorProcessed = CTheme.GetColor(_Theme.SColorName);
}
public void ReloadTextures()
{
UnloadTextures();
LoadTextures();
}
#region ThemeEdit
public void MoveElement(int stepX, int stepY)
{
SRectF rect = Rect;
rect.X += stepX;
rect.Y += stepY;
Rect = rect;
}
public void ResizeElement(int stepW, int stepH)
{
SRectF rect = Rect;
rect.W += stepW;
if (rect.W <= 0)
rect.W = 1;
rect.H += stepH;
if (rect.H <= 0)
rect.H = 1;
Rect = rect;
}
#endregion ThemeEdit
}
}
File diff suppressed because it is too large. Load diff
+795
View File
@@ -0,0 +1,795 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Menu
{
struct SThemeSelectSlide
{
public string Name;
public string TextureName;
public string TextureArrowLeftName;
public string TextureArrowRightName;
public string STextureName;
public string STextureArrowLeftName;
public string STextureArrowRightName;
public string HTextureName;
public string ColorName;
public string SColorName;
public string HColorName;
public string ArrowColorName;
public string SArrowColorName;
public string TextColorName;
public string STextColorName;
public string TextFont;
public EStyle TextStyle;
}
class CSelectSlide : IMenuElement
{
private SThemeSelectSlide _Theme;
private bool _ThemeLoaded;
public SRectF Rect;
public SRectF RectArrowLeft;
public SRectF RectArrowRight;
public SColorF Color;
public SColorF SColor;
public SColorF HColor;
public SColorF ColorArrow;
public SColorF SColorArrow;
public SColorF TextColor;
public SColorF STextColor;
public float TextH;
public float MaxW;
private bool _Selected;
public bool Selected
{
get { return _Selected; }
set
{
_Selected = value;
if (!value)
{
_ArrowLeftSelected = false;
_ArrowRightSelected = false;
}
}
}
public bool Visible = true;
public bool Highlighted = false;
private bool _ArrowLeftSelected;
private bool _ArrowRightSelected;
private List<string> _ValueNames;
private List<STexture> _Textures;
private List<int> _ValueIndexes;
private List<SRectF> _ValueBounds = new List<SRectF>();
public bool WithTextures;
private int _Selection = -1;
public int Selection
{
get { return _Selection; }
set
{
if (value >= 0 && value < _ValueNames.Count)
{
_Selection = value;
}
}
}
public int ValueIndex
{
get
{
if (_Selection >= 0 && _ValueIndexes.Count > _Selection)
return _ValueIndexes[_Selection];
else return -1;
}
}
private int _NumVisible = -1;
public int NumVisible
{
get { return _NumVisible; }
set
{
if (value > 0)
_NumVisible = value;
_ValueBounds.Clear();
}
}
public CSelectSlide()
{
_Theme = new SThemeSelectSlide();
_ThemeLoaded = false;
Rect = new SRectF();
RectArrowLeft = new SRectF();
RectArrowRight = new SRectF();
Color = new SColorF();
SColor = new SColorF();
ColorArrow = new SColorF();
SColorArrow = new SColorF();
TextColor = new SColorF();
STextColor = new SColorF();
TextH = 1f;
MaxW = 0f;
_Selected = false;
_Textures = new List<STexture>();
_ValueIndexes = new List<int>();
_ValueNames = new List<string>();
}
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
string item = XmlPath + "/" + ElementName;
_ThemeLoaded = true;
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/Skin", navigator, ref _Theme.TextureName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinArrowLeft", navigator, ref _Theme.TextureArrowLeftName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinArrowRight", navigator, ref _Theme.TextureArrowRightName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinSelected", navigator, ref _Theme.STextureName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinArrowLeftSelected", navigator, ref _Theme.STextureArrowLeftName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinArrowRightSelected", navigator, ref _Theme.STextureArrowRightName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinHighlighted", navigator, ref _Theme.HTextureName, String.Empty);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/X", navigator, ref Rect.X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Y", navigator, ref Rect.Y);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Z", navigator, ref Rect.Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/W", navigator, ref Rect.W);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/H", navigator, ref Rect.H);
if (CHelper.GetValueFromXML(item + "/Color", navigator, ref _Theme.ColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.ColorName, SkinIndex, ref Color);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/R", navigator, ref Color.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/G", navigator, ref Color.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/B", navigator, ref Color.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/A", navigator, ref Color.A);
}
if (CHelper.GetValueFromXML(item + "/SColor", navigator, ref _Theme.SColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.SColorName, SkinIndex, ref SColor);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SR", navigator, ref SColor.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SG", navigator, ref SColor.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SB", navigator, ref SColor.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SA", navigator, ref SColor.A);
}
if (CHelper.GetValueFromXML(item + "/HColor", navigator, ref _Theme.HColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.HColorName, SkinIndex, ref HColor);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/HR", navigator, ref HColor.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/HG", navigator, ref HColor.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/HB", navigator, ref HColor.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/HA", navigator, ref HColor.A);
}
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowLeftX", navigator, ref RectArrowLeft.X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowLeftY", navigator, ref RectArrowLeft.Y);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowLeftZ", navigator, ref RectArrowLeft.Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowLeftW", navigator, ref RectArrowLeft.W);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowLeftH", navigator, ref RectArrowLeft.H);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowRightX", navigator, ref RectArrowRight.X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowRightY", navigator, ref RectArrowRight.Y);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowRightZ", navigator, ref RectArrowRight.Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowRightW", navigator, ref RectArrowRight.W);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowRightH", navigator, ref RectArrowRight.H);
if (CHelper.GetValueFromXML(item + "/ArrowColor", navigator, ref _Theme.ArrowColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.ArrowColorName, SkinIndex, ref ColorArrow);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowR", navigator, ref ColorArrow.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowG", navigator, ref ColorArrow.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowB", navigator, ref ColorArrow.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowA", navigator, ref ColorArrow.A);
}
if (CHelper.GetValueFromXML(item + "/ArrowSColor", navigator, ref _Theme.SArrowColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.SArrowColorName, SkinIndex, ref SColorArrow);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowSR", navigator, ref SColorArrow.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowSG", navigator, ref SColorArrow.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowSB", navigator, ref SColorArrow.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/ArrowSA", navigator, ref SColorArrow.A);
}
if (CHelper.GetValueFromXML(item + "/TextColor", navigator, ref _Theme.TextColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.TextColorName, SkinIndex, ref TextColor);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextR", navigator, ref TextColor.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextG", navigator, ref TextColor.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextB", navigator, ref TextColor.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextA", navigator, ref TextColor.A);
}
if (CHelper.GetValueFromXML(item + "/TextSColor", navigator, ref _Theme.STextColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.STextColorName, SkinIndex, ref STextColor);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextSR", navigator, ref STextColor.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextSG", navigator, ref STextColor.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextSB", navigator, ref STextColor.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextSA", navigator, ref STextColor.A);
}
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextH", navigator, ref TextH);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/TextMaxW", navigator, ref MaxW);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/TextFont", navigator, ref _Theme.TextFont, "Normal");
_ThemeLoaded &= CHelper.TryGetEnumValueFromXML<EStyle>(item + "/TextStyle", navigator, ref _Theme.TextStyle);
_ThemeLoaded &= CHelper.TryGetIntValueFromXML(item + "/NumVisible", navigator, ref _NumVisible);
if (_ThemeLoaded)
{
_Theme.Name = ElementName;
LoadTextures();
}
return _ThemeLoaded;
}
public bool SaveTheme(XmlWriter writer)
{
if (_ThemeLoaded)
{
writer.WriteStartElement(_Theme.Name);
writer.WriteComment("<Skin>: Texture name");
writer.WriteElementString("Skin", _Theme.TextureName);
writer.WriteComment("<SkinArrowLeft>: Texture name of left arrow");
writer.WriteElementString("SkinArrowLeft", _Theme.TextureArrowLeftName);
writer.WriteComment("<SkinArrowRight>: Texture name of right arrow");
writer.WriteElementString("SkinArrowRight", _Theme.TextureArrowRightName);
writer.WriteComment("<SkinSelected>: Texture name for selected SelectSlide");
writer.WriteElementString("SkinSelected", _Theme.STextureName);
writer.WriteComment("<SkinArrowLeftSelected>: Texture name of selected left arrow");
writer.WriteElementString("SkinArrowLeftSelected", _Theme.STextureArrowLeftName);
writer.WriteComment("<SkinArrowRightSelected>: Texture name of selected right arrow");
writer.WriteElementString("SkinArrowRightSelected", _Theme.STextureArrowRightName);
writer.WriteComment("<SkinHighlighted>: Texture name for highlighted SelectSlide");
writer.WriteElementString("SkinHighlighted", _Theme.HTextureName);
writer.WriteComment("<X>, <Y>, <Z>, <W>, <H>: SelectSlide position, width and height");
writer.WriteElementString("X", Rect.X.ToString("#0"));
writer.WriteElementString("Y", Rect.Y.ToString("#0"));
writer.WriteElementString("Z", Rect.Z.ToString("#0.00"));
writer.WriteElementString("W", Rect.W.ToString("#0"));
writer.WriteElementString("H", Rect.H.ToString("#0"));
writer.WriteComment("<ArrowLeftX>, <ArrowLeftY>, <ArrowLeftZ>, <ArrowLeftW>, <ArrowLeftH>: Left arrow position, width and height");
writer.WriteElementString("ArrowLeftX", RectArrowLeft.X.ToString("#0"));
writer.WriteElementString("ArrowLeftY", RectArrowLeft.Y.ToString("#0"));
writer.WriteElementString("ArrowLeftZ", RectArrowLeft.Z.ToString("#0.00"));
writer.WriteElementString("ArrowLeftW", RectArrowLeft.W.ToString("#0"));
writer.WriteElementString("ArrowLeftH", RectArrowLeft.H.ToString("#0"));
writer.WriteComment("<ArrowRightX>, <ArrowRightY>, <ArrowRightZ>, <ArrowRightW>, <ArrowRightH>: Right arrow position, width and height");
writer.WriteElementString("ArrowRightX", RectArrowRight.X.ToString("#0"));
writer.WriteElementString("ArrowRightY", RectArrowRight.Y.ToString("#0"));
writer.WriteElementString("ArrowRightZ", RectArrowRight.Z.ToString("#0.00"));
writer.WriteElementString("ArrowRightW", RectArrowRight.W.ToString("#0"));
writer.WriteElementString("ArrowRightH", RectArrowRight.H.ToString("#0"));
writer.WriteComment("<Color>: SelectSlide color from ColorScheme (high priority)");
writer.WriteComment("or <R>, <G>, <B>, <A> (lower priority)");
if (_Theme.ColorName != String.Empty)
{
writer.WriteElementString("Color", _Theme.ColorName);
}
else
{
writer.WriteElementString("R", Color.R.ToString("#0.00"));
writer.WriteElementString("G", Color.G.ToString("#0.00"));
writer.WriteElementString("B", Color.B.ToString("#0.00"));
writer.WriteElementString("A", Color.A.ToString("#0.00"));
}
writer.WriteComment("<SColor>: Selected SelectSlide color from ColorScheme (high priority)");
writer.WriteComment("or <SR>, <SG>, <SB>, <SA> (lower priority)");
if (_Theme.SColorName != String.Empty)
{
writer.WriteElementString("SColor", _Theme.SColorName);
}
else
{
writer.WriteElementString("SR", SColor.R.ToString("#0.00"));
writer.WriteElementString("SG", SColor.G.ToString("#0.00"));
writer.WriteElementString("SB", SColor.B.ToString("#0.00"));
writer.WriteElementString("SA", SColor.A.ToString("#0.00"));
}
writer.WriteComment("<HColor>: Highlighted SelectSlide color from ColorScheme (high priority)");
writer.WriteComment("or <HR>, <HG>, <HB>, <HA> (lower priority)");
if (_Theme.HColorName != String.Empty)
{
writer.WriteElementString("HColor", _Theme.HColorName);
}
else
{
writer.WriteElementString("HR", HColor.R.ToString("#0.00"));
writer.WriteElementString("HG", HColor.G.ToString("#0.00"));
writer.WriteElementString("HB", HColor.B.ToString("#0.00"));
writer.WriteElementString("HA", HColor.A.ToString("#0.00"));
}
writer.WriteComment("<ArrowColor>: Arrow color from ColorScheme (high priority)");
writer.WriteComment("or <ArrowR>, <ArrowG>, <ArrowB>, <ArrowA> (lower priority)");
if (_Theme.ArrowColorName != String.Empty)
{
writer.WriteElementString("ArrowColor", _Theme.ArrowColorName);
}
else
{
writer.WriteElementString("ArrowR", ColorArrow.R.ToString("#0.00"));
writer.WriteElementString("ArrowG", ColorArrow.G.ToString("#0.00"));
writer.WriteElementString("ArrowB", ColorArrow.B.ToString("#0.00"));
writer.WriteElementString("ArrowA", ColorArrow.A.ToString("#0.00"));
}
writer.WriteComment("<ArrowSColor>: Selected arrow color from ColorScheme (high priority)");
writer.WriteComment("or <ArrowSR>, <ArrowSG>, <ArrowSB>, <ArrowSA> (lower priority)");
if (_Theme.SArrowColorName != String.Empty)
{
writer.WriteElementString("ArrowSColor", _Theme.SArrowColorName);
}
else
{
writer.WriteElementString("ArrowSR", SColorArrow.R.ToString("#0.00"));
writer.WriteElementString("ArrowSG", SColorArrow.G.ToString("#0.00"));
writer.WriteElementString("ArrowSB", SColorArrow.B.ToString("#0.00"));
writer.WriteElementString("ArrowSA", SColorArrow.A.ToString("#0.00"));
}
writer.WriteComment("<TextColor>: Text color from ColorScheme (high priority)");
writer.WriteComment("or <TextR>, <TextG>, <TextB>, <TextA> (lower priority)");
if (_Theme.TextColorName != String.Empty)
{
writer.WriteElementString("TextColor", _Theme.TextColorName);
}
else
{
writer.WriteElementString("TextR", TextColor.R.ToString("#0.00"));
writer.WriteElementString("TextG", TextColor.G.ToString("#0.00"));
writer.WriteElementString("TextB", TextColor.B.ToString("#0.00"));
writer.WriteElementString("TextA", TextColor.A.ToString("#0.00"));
}
writer.WriteComment("<TextSColor>: Selected text color from ColorScheme (high priority)");
writer.WriteComment("or <TextSR>, <TextSG>, <TextSB>, <TextSA> (lower priority)");
if (_Theme.STextColorName != String.Empty)
{
writer.WriteElementString("TextSColor", _Theme.STextColorName);
}
else
{
writer.WriteElementString("TextSR", STextColor.R.ToString("#0.00"));
writer.WriteElementString("TextSG", STextColor.G.ToString("#0.00"));
writer.WriteElementString("TextSB", STextColor.B.ToString("#0.00"));
writer.WriteElementString("TextSA", STextColor.A.ToString("#0.00"));
}
writer.WriteComment("<TextH>: Text height");
writer.WriteElementString("TextH", TextH.ToString("#0.00"));
writer.WriteComment("<TextMaxW>: Maximum text width (if exists)");
writer.WriteElementString("TextMaxW", MaxW.ToString("#0.00"));
writer.WriteComment("<TextFont>: Text font name");
writer.WriteElementString("TextFont", _Theme.TextFont);
writer.WriteComment("<TextStyle>: Text style: " + CConfig.ListStrings(Enum.GetNames(typeof(EStyle))));
writer.WriteElementString("TextStyle", Enum.GetName(typeof(EStyle), _Theme.TextStyle));
writer.WriteComment("<NumVisible>: Number of visible elements in the slide");
writer.WriteElementString("NumVisible", _NumVisible.ToString());
writer.WriteEndElement();
return true;
}
return false;
}
public void AddValue(string value)
{
AddValue(value, new STexture(-1));
_ValueBounds.Clear();
}
public void AddValue(string value, STexture texture)
{
AddValue(value, texture, _ValueIndexes.Count);
}
public void AddValue(string value, STexture texture, int valueIndex)
{
_ValueNames.Add(value);
_Textures.Add(texture);
_ValueIndexes.Add(valueIndex);
if (Selection == -1)
Selection = 0;
_ValueBounds.Clear();
}
public void AddValues(string[] values)
{
foreach (string value in values)
{
AddValue(value, new STexture(-1));
}
_ValueBounds.Clear();
}
public void AddValues(string[] values, STexture[] textures)
{
if (values.Length != textures.Length)
return;
for (int i = 0; i < values.Length; i++)
{
AddValue(values[i], textures[i]);
}
if (Selection == -1)
Selection = 0;
_ValueBounds.Clear();
}
public void SetValues<T>(int selection)
{
AddValues(Enum.GetNames(typeof(T)));
Selection = selection;
}
public void RenameValue(string NewName)
{
RenameValue(Selection, NewName);
}
public void RenameValue(int selection, string NewName)
{
RenameValue(selection, NewName, new STexture(-1));
}
public void RenameValue(int selection, string NewName, STexture NewTexture)
{
if (selection < 0 && selection >= _ValueNames.Count)
return;
_ValueNames[selection] = NewName;
_Textures[selection] = NewTexture;
}
public bool NextValue()
{
if (Selection < _ValueNames.Count - 1)
{
Selection++;
return true;
}
return false;
}
public bool PrevValue()
{
if (Selection > 0)
{
Selection--;
return true;
}
return false;
}
public void FirstValue()
{
if (_ValueNames.Count > 0)
Selection = 0;
}
public void LastValue()
{
if (_ValueNames.Count > 0)
Selection = _ValueNames.Count - 1;
}
public void Clear()
{
_Selection = -1;
_ValueNames.Clear();
_Textures.Clear();
_ValueBounds.Clear();
_ValueIndexes.Clear();
}
public void ProcessMouseMove(int x, int y)
{
_ArrowLeftSelected = CHelper.IsInBounds(RectArrowLeft, x, y);
_ArrowRightSelected = CHelper.IsInBounds(RectArrowRight, x, y);
}
public void ProcessMouseLBClick(int x, int y)
{
_ArrowLeftSelected = CHelper.IsInBounds(RectArrowLeft, x, y);
_ArrowRightSelected = CHelper.IsInBounds(RectArrowRight, x, y);
if (_ArrowLeftSelected)
PrevValue();
if (_ArrowRightSelected)
NextValue();
for (int i = 0; i < _ValueBounds.Count; i++)
{
if (CHelper.IsInBounds(_ValueBounds[i], x, y))
{
int offset = _Selection - (int)_NumVisible / 2;
if (_ValueNames.Count - _NumVisible - offset < 0)
offset = _ValueNames.Count - _NumVisible;
if (offset < 0)
offset = 0;
Selection = i + offset;
_ValueBounds.Clear();
break;
}
}
}
public void Draw()
{
if (!Visible && CSettings.GameState != EGameState.EditTheme)
return;
STexture Texture = CTheme.GetSkinTexture(_Theme.TextureName);
STexture TextureArrowLeft = CTheme.GetSkinTexture(_Theme.TextureArrowLeftName);
STexture TextureArrowRight = CTheme.GetSkinTexture(_Theme.TextureArrowRightName);
STexture STexture = CTheme.GetSkinTexture(_Theme.STextureName);
STexture STextureArrowLeft = CTheme.GetSkinTexture(_Theme.STextureArrowLeftName);
STexture STextureArrowRight = CTheme.GetSkinTexture(_Theme.STextureArrowRightName);
STexture HTexture = CTheme.GetSkinTexture(_Theme.HTextureName);
if (Selected)
{
if (Highlighted)
CDraw.DrawTexture(HTexture, Rect, HColor);
else
CDraw.DrawTexture(STexture, Rect, SColor);
}
else
CDraw.DrawTexture(Texture, Rect, Color);
if (_Selection > 0 || CSettings.GameState == EGameState.EditTheme)
{
if (_ArrowLeftSelected)
CDraw.DrawTexture(STextureArrowLeft, RectArrowLeft, SColorArrow);
else
CDraw.DrawTexture(TextureArrowLeft, RectArrowLeft, ColorArrow);
}
if (_Selection < _ValueNames.Count - 1 || CSettings.GameState == EGameState.EditTheme)
{
if (_ArrowRightSelected)
CDraw.DrawTexture(STextureArrowRight, RectArrowRight, SColorArrow);
else
CDraw.DrawTexture(TextureArrowRight, RectArrowRight, ColorArrow);
}
if (_NumVisible < 1 || _ValueNames.Count == 0)
return;
float x = Rect.X + Rect.W * 0.1f;
float dx = Rect.W * 0.8f / _NumVisible;
//float y = Rect.Y + (Rect.H - TextH);
int offset = _Selection - (int)_NumVisible/2;
if (_ValueNames.Count - _NumVisible - offset < 0)
offset = _ValueNames.Count - _NumVisible;
if (offset < 0)
offset = 0;
int numvis = _NumVisible;
if (_ValueNames.Count < numvis)
numvis = _ValueNames.Count;
_ValueBounds.Clear();
for (int i = 0; i < numvis; i++)
{
CText Text = new CText(0, 0, 0, TextH, MaxW, EAlignment.Center, _Theme.TextStyle, _Theme.TextFont, TextColor, _ValueNames[i + offset]);
SColorF Alpha = new SColorF(1f, 1f, 1f, 0.35f);
if (i + offset == _Selection)
{
Text.Color = STextColor;
Alpha = new SColorF(1f, 1f, 1f, 1f);
}
RectangleF bounds = CDraw.GetTextBounds(Text);
Text.X = x + dx/2f + dx * i;
if (!WithTextures)
Text.Y = (int)(Rect.Y + (Rect.H - bounds.Height) / 2);
else
Text.Y = (int)(Rect.Y + (Rect.H - bounds.Height));
Text.Z = Rect.Z;
Text.Draw();
if (WithTextures)
{
float dh = Text.Y - Rect.Y - Rect.H * 0.1f;
SRectF rect = new SRectF(Text.X - dh / 2, Rect.Y + Rect.H * 0.05f, dh, dh, Rect.Z);
CDraw.DrawTexture(_Textures[i + offset], rect, Alpha);
_ValueBounds.Add(rect);
}
else
{
_ValueBounds.Add(new SRectF(Text.X - bounds.Width/2f, Text.Y, bounds.Width, bounds.Height, Rect.Z));
}
}
}
public void UnloadTextures()
{
}
public void LoadTextures()
{
if (_Theme.ColorName != String.Empty)
Color = CTheme.GetColor(_Theme.ColorName);
if (_Theme.SColorName != String.Empty)
SColor = CTheme.GetColor(_Theme.SColorName);
if (_Theme.HColorName != String.Empty)
HColor = CTheme.GetColor(_Theme.HColorName);
if (_Theme.ArrowColorName != String.Empty)
ColorArrow = CTheme.GetColor(_Theme.ArrowColorName);
if (_Theme.SArrowColorName != String.Empty)
SColorArrow = CTheme.GetColor(_Theme.SArrowColorName);
if (_Theme.TextColorName != String.Empty)
TextColor = CTheme.GetColor(_Theme.TextColorName);
if (_Theme.SColorName != String.Empty)
STextColor = CTheme.GetColor(_Theme.STextColorName);
}
public void ReloadTextures()
{
UnloadTextures();
LoadTextures();
}
#region ThemeEdit
public void MoveElement(int stepX, int stepY)
{
if (!_ArrowLeftSelected && !_ArrowRightSelected)
{
Rect.X += stepX;
Rect.Y += stepY;
}
if (_ArrowLeftSelected)
{
RectArrowLeft.X += stepX;
RectArrowLeft.Y += stepY;
}
if (_ArrowRightSelected)
{
RectArrowRight.X += stepX;
RectArrowRight.Y += stepY;
}
}
public void ResizeElement(int stepW, int stepH)
{
if (!_ArrowLeftSelected && !_ArrowRightSelected)
{
Rect.W += stepW;
if (Rect.W <= 0)
Rect.W = 1;
Rect.H += stepH;
if (Rect.H <= 0)
Rect.H = 1;
}
if (_ArrowLeftSelected)
{
RectArrowLeft.W += stepW;
if (RectArrowLeft.W <= 0)
RectArrowLeft.W = 1;
RectArrowLeft.H += stepH;
if (RectArrowLeft.H <= 0)
RectArrowLeft.H = 1;
}
if (_ArrowRightSelected)
{
RectArrowRight.W += stepW;
if (RectArrowRight.W <= 0)
RectArrowRight.W = 1;
RectArrowRight.H += stepH;
if (RectArrowRight.H <= 0)
RectArrowRight.H = 1;
}
}
#endregion ThemeEdit
}
}
+292
View File
@@ -0,0 +1,292 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Menu
{
struct SThemeStatic
{
public string Name;
public string TextureName;
public string ColorName;
}
class CStatic : IMenuElement
{
private SThemeStatic _Theme;
private bool _ThemeLoaded;
private STexture _Texture;
public STexture Texture
{
get
{
if (_Texture.index != -1)
return _Texture;
else
return CTheme.GetSkinTexture(_Theme.TextureName);
}
set { _Texture = value; }
}
public SColorF Color;
public SRectF Rect;
public bool Reflection;
public float ReflectionSpace;
public float ReflectionHeight;
public bool Selected;
public bool Visible;
public float Alpha;
public CStatic()
{
_Theme = new SThemeStatic();
_ThemeLoaded = false;
_Texture = new STexture(-1);
Color = new SColorF();
Rect = new SRectF();
Reflection = false;
ReflectionSpace = 0f;
ReflectionHeight = 0f;
Selected = false;
Alpha = 1f;
Visible = true;
}
public CStatic(STexture texture, SColorF color, SRectF rect)
{
_Theme = new SThemeStatic();
_ThemeLoaded = false;
_Texture = texture;
Color = color;
Rect = rect;
Reflection = false;
ReflectionSpace = 0f;
ReflectionHeight = 0f;
Selected = false;
Alpha = 1f;
Visible = true;
}
public CStatic(string TextureSkinName, SColorF color, SRectF rect)
{
_Theme = new SThemeStatic();
_Theme.TextureName = TextureSkinName;
_ThemeLoaded = false;
_Texture = new STexture(-1);
Color = color;
Rect = rect;
Reflection = false;
ReflectionSpace = 0f;
ReflectionHeight = 0f;
Selected = false;
Alpha = 1f;
Visible = true;
}
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
string item = XmlPath + "/" + ElementName;
_ThemeLoaded = true;
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/Skin", navigator, ref _Theme.TextureName, String.Empty);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/X", navigator, ref Rect.X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Y", navigator, ref Rect.Y);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Z", navigator, ref Rect.Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/W", navigator, ref Rect.W);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/H", navigator, ref Rect.H);
if (CHelper.GetValueFromXML(item + "/Color", navigator, ref _Theme.ColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.ColorName, SkinIndex, ref Color);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/R", navigator, ref Color.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/G", navigator, ref Color.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/B", navigator, ref Color.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/A", navigator, ref Color.A);
}
if (CHelper.ItemExistsInXML(item + "/Reflection", navigator))
{
Reflection = true;
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Reflection/Space", navigator, ref ReflectionSpace);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Reflection/Height", navigator, ref ReflectionHeight);
}
else
Reflection = false;
if (_ThemeLoaded)
{
_Theme.Name = ElementName;
LoadTextures();
}
return _ThemeLoaded;
}
public bool SaveTheme(XmlWriter writer)
{
if (_ThemeLoaded)
{
writer.WriteStartElement(_Theme.Name);
writer.WriteComment("<Skin>: Texture name");
writer.WriteElementString("Skin", _Theme.TextureName);
writer.WriteComment("<X>, <Y>, <Z>, <W>, <H>: Static position, width and height");
writer.WriteElementString("X", Rect.X.ToString("#0"));
writer.WriteElementString("Y", Rect.Y.ToString("#0"));
writer.WriteElementString("Z", Rect.Z.ToString("#0.00"));
writer.WriteElementString("W", Rect.W.ToString("#0"));
writer.WriteElementString("H", Rect.H.ToString("#0"));
writer.WriteComment("<Color>: Static color from ColorScheme (high priority)");
writer.WriteComment("or <R>, <G>, <B>, <A> (lower priority)");
if (_Theme.ColorName != String.Empty)
{
writer.WriteElementString("Color", _Theme.ColorName);
}
else
{
writer.WriteElementString("R", Color.R.ToString("#0.00"));
writer.WriteElementString("G", Color.G.ToString("#0.00"));
writer.WriteElementString("B", Color.B.ToString("#0.00"));
writer.WriteElementString("A", Color.A.ToString("#0.00"));
}
writer.WriteComment("<Reflection> If exists:");
writer.WriteComment(" <Space>: Reflection Space");
writer.WriteComment(" <Height>: Reflection Height");
if (Reflection)
{
writer.WriteStartElement("Reflection");
writer.WriteElementString("Space", ReflectionSpace.ToString("#0"));
writer.WriteElementString("Height", ReflectionHeight.ToString("#0"));
writer.WriteEndElement();
}
writer.WriteEndElement();
return true;
}
return false;
}
public void Draw()
{
Draw(1f, Rect.Z, false, false);
}
public void Draw(bool aspect)
{
Draw(1f, Rect.Z, aspect, false);
}
public void Draw(float scale, bool aspect)
{
Draw(scale, Rect.Z, aspect, false);
}
public void ForceDraw()
{
Draw(1f, Rect.Z, false, true);
}
public void Draw(float scale, float z, bool aspect, bool ForceDraw)
{
STexture texture;
if (_Texture.index != -1)
texture = _Texture;
else
texture = CTheme.GetSkinTexture(_Theme.TextureName);
SRectF bounds = new SRectF(
Rect.X - Rect.W * (scale - 1f),
Rect.Y - Rect.H * (scale - 1f),
Rect.W + 2 * Rect.W * (scale - 1f),
Rect.H + 2 * Rect.H * (scale - 1f),
z);
SRectF rect = bounds;
if (aspect)
{
RectangleF bounds2 = new RectangleF(bounds.X, bounds.Y, bounds.W, bounds.H);
RectangleF rect2 = new RectangleF(0f, 0f, texture.width, texture.height);
CHelper.SetRect(bounds2, ref rect2, texture.width / texture.height, EAspect.Crop);
rect.X = rect2.X;
rect.Y = rect2.Y;
rect.W = rect2.Width;
rect.H = rect2.Height;
}
SColorF color = new SColorF(Color.R, Color.G, Color.B, Color.A * Alpha);
if (Visible || ForceDraw || (CSettings.GameState == EGameState.EditTheme))
{
CDraw.DrawTexture(texture, rect, color, bounds);
if (Reflection)
{
CDraw.DrawTextureReflection(texture, rect, color, bounds, ReflectionSpace, ReflectionHeight);
}
}
if (Selected && (CSettings.GameState == EGameState.EditTheme))
{
CDraw.DrawColor(new SColorF(1f, 1f, 1f, 0.5f), rect);
}
}
public void UnloadTextures()
{
}
public void LoadTextures()
{
if (_Theme.ColorName != String.Empty)
Color = CTheme.GetColor(_Theme.ColorName);
}
public void ReloadTextures()
{
UnloadTextures();
LoadTextures();
}
#region ThemeEdit
public void MoveElement(int stepX, int stepY)
{
Rect.X += stepX;
Rect.Y += stepY;
}
public void ResizeElement(int stepW, int stepH)
{
Rect.W += stepW;
if (Rect.W <= 0)
Rect.W = 1;
Rect.H += stepH;
if (Rect.H <= 0)
Rect.H = 1;
}
#endregion ThemeEdit
}
}
+575
View File
@@ -0,0 +1,575 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Menu
{
struct SThemeText
{
public string Name;
public string ColorName;
public string SColorName; //for Buttons
}
class CText : IMenuElement
{
private SThemeText _Theme;
private bool _ThemeLoaded;
private bool _ButtonText;
public float X; //left
public float Y; //higher
public float Z;
public float Height;
public float MaxWidth;
public SRectF Bounds;
public EAlignment Align;
public EStyle Style;
public string Fon;
public SColorF Color; //normal Color
public SColorF SColor; //selected Color for Buttons
public bool Reflection;
public float ReflectionSpace;
public float ReflectionHeight;
public string Text;
public bool Selected;
public bool Visible = true;
public float Alpha = 1f;
public CText()
{
_Theme = new SThemeText();
_ThemeLoaded = false;
_ButtonText = false;
X = 0f;
Y = 0f;
Z = 0f;
Height = 1f;
MaxWidth = 0f;
Bounds = new SRectF();
Align = EAlignment.Left;
Style = EStyle.Normal;
Fon = "Normal";
Color = new SColorF();
SColor = new SColorF();
Reflection = false;
ReflectionSpace = 0f;
ReflectionHeight = 0f;
Text = String.Empty;
Selected = false;
Visible = true;
Alpha = 1f;
}
public CText(float x, float y, float z, EAlignment align, float h, float mw, float r, float g, float b, float a, EStyle style, string font, string text, float rspace, float rheight)
{
_Theme = new SThemeText();
_ThemeLoaded = false;
_ButtonText = false;
X = x;
Y = y;
Z = z;
Height = h;
MaxWidth = mw;
Align = align;
Style = style;
Fon = font;
Color = new SColorF(r, g, b, a);
SColor = new SColorF(r, g, b, a);
text = Text;
Selected = false;
if (MaxWidth > 0)
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, MaxWidth, 3f * CSettings.iRenderH, 0f);
}
else
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, 3f * CSettings.iRenderW, 3f * CSettings.iRenderH, 0f);
}
Reflection = true;
ReflectionSpace = rspace;
ReflectionHeight = rheight;
}
public CText(float x, float y, float z, EAlignment align, float h, float mw, float r, float g, float b, float a, EStyle style, string font, string text)
{
_Theme = new SThemeText();
_ThemeLoaded = false;
_ButtonText = false;
X = x;
Y = y;
Z = z;
Height = h;
MaxWidth = mw;
Align = align;
Style = style;
Fon = font;
Color = new SColorF(r, g, b, a);
SColor = new SColorF(r, g, b, a);
text = Text;
Selected = false;
if (MaxWidth > 0)
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, MaxWidth, 3f * CSettings.iRenderH, 0f);
}
else
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, 3f * CSettings.iRenderW, 3f * CSettings.iRenderH, 0f);
}
Reflection = false;
}
public CText(float x, float y, float z, float h, float mw, EAlignment align, EStyle style, string font, SColorF col, string text, float rspace, float rheight)
{
_Theme = new SThemeText();
_ThemeLoaded = false;
_ButtonText = false;
X = x;
Y = y;
Z = z;
Height = h;
MaxWidth = mw;
Align = align;
Style = style;
Fon = font;
Color = col;
SColor = new SColorF(col);
Text = text;
Selected = false;
if (MaxWidth > 0)
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, MaxWidth, 3f * CSettings.iRenderH, 0f);
}
else
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, 3f * CSettings.iRenderW, 3f * CSettings.iRenderH, 0f);
}
Reflection = true;
ReflectionSpace = rspace;
ReflectionHeight = rheight;
}
public CText(float x, float y, float z, float h, float mw, EAlignment align, EStyle style, string font, SColorF col, string text)
{
_Theme = new SThemeText();
_ThemeLoaded = false;
_ButtonText = false;
X = x;
Y = y;
Z = z;
Height = h;
MaxWidth = mw;
Align = align;
Style = style;
Fon = font;
Color = col;
SColor = new SColorF(col);
Text = text;
Selected = false;
if (MaxWidth > 0)
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, MaxWidth, 3f * CSettings.iRenderH, 0f);
}
else
{
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, 3f * CSettings.iRenderW, 3f * CSettings.iRenderH, 0f);
}
Reflection = false;
}
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
return LoadTheme(XmlPath, ElementName, navigator, SkinIndex, false);
}
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex, bool ButtonText)
{
string item = XmlPath + "/" + ElementName;
_ThemeLoaded = true;
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/X", navigator, ref X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Y", navigator, ref Y);
if (!ButtonText)
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Z", navigator, ref Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/H", navigator, ref Height);
CHelper.TryGetFloatValueFromXML(item + "/MaxW", navigator, ref MaxWidth);
if (CHelper.GetValueFromXML(item + "/Color", navigator, ref _Theme.ColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.ColorName, SkinIndex, ref Color);
}
else
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/R", navigator, ref Color.R);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/G", navigator, ref Color.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/B", navigator, ref Color.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/A", navigator, ref Color.A);
}
if (CHelper.GetValueFromXML(item + "/SColor", navigator, ref _Theme.SColorName, String.Empty))
{
_ThemeLoaded &= CTheme.GetColor(_Theme.SColorName, SkinIndex, ref SColor);
}
else
{
if (CHelper.TryGetFloatValueFromXML(item + "/SR", navigator, ref SColor.R))
{
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SG", navigator, ref SColor.G);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SB", navigator, ref SColor.B);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/SA", navigator, ref SColor.A);
}
}
_ThemeLoaded &= CHelper.TryGetEnumValueFromXML<EAlignment>(item + "/Align", navigator, ref Align);
_ThemeLoaded &= CHelper.TryGetEnumValueFromXML<EStyle>(item + "/Style", navigator, ref Style);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/Font", navigator, ref Fon, "Normal");
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/Text", navigator, ref Text, String.Empty);
if (CHelper.ItemExistsInXML(item + "/Reflection", navigator) && !ButtonText)
{
Reflection = true;
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Reflection/Space", navigator, ref ReflectionSpace);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + "/Reflection/Height", navigator, ref ReflectionHeight);
}
else
Reflection = false;
if (_ThemeLoaded)
{
_Theme.Name = ElementName;
LoadTextures();
if (MaxWidth > 0)
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, MaxWidth, 3f * CSettings.iRenderH, 0f);
else
Bounds = new SRectF(-CSettings.iRenderW, -CSettings.iRenderH, 3f * CSettings.iRenderW, 3f * CSettings.iRenderH, 0f);
_ButtonText = ButtonText;
}
return _ThemeLoaded;
}
public bool SaveTheme(XmlWriter writer)
{
if (_ThemeLoaded || _ButtonText)
{
writer.WriteStartElement(_Theme.Name);
writer.WriteComment("<X>, <Y>: Text position");
writer.WriteElementString("X", X.ToString("#0"));
writer.WriteElementString("Y", Y.ToString("#0"));
if (!_ButtonText)
{
writer.WriteComment("<Z>: Text position");
writer.WriteElementString("Z", Z.ToString("#0.00"));
}
writer.WriteComment("<H>: Text height");
writer.WriteElementString("H", Height.ToString("#0"));
writer.WriteComment("<MaxW>: Maximum text width (if exists)");
if (MaxWidth > 0)
writer.WriteElementString("MaxW", MaxWidth.ToString("#0"));
writer.WriteComment("<Color>: Text color from ColorScheme (high priority)");
writer.WriteComment("or <R>, <G>, <B>, <A> (lower priority)");
if (_Theme.ColorName != String.Empty)
{
writer.WriteElementString("Color", _Theme.ColorName);
}
else
{
writer.WriteElementString("R", Color.R.ToString("#0.00"));
writer.WriteElementString("G", Color.G.ToString("#0.00"));
writer.WriteElementString("B", Color.B.ToString("#0.00"));
writer.WriteElementString("A", Color.A.ToString("#0.00"));
}
writer.WriteComment("<SColor>: Selected Text color from ColorScheme (high priority)");
writer.WriteComment("or <SR>, <SG>, <SB>, <SA> (lower priority)");
if (_Theme.SColorName != String.Empty)
{
writer.WriteElementString("SColor", _Theme.SColorName);
}
else
{
writer.WriteElementString("SR", SColor.R.ToString("#0.00"));
writer.WriteElementString("SG", SColor.G.ToString("#0.00"));
writer.WriteElementString("SB", SColor.B.ToString("#0.00"));
writer.WriteElementString("SA", SColor.A.ToString("#0.00"));
}
writer.WriteComment("<Align>: Text align: " + CConfig.ListStrings(Enum.GetNames(typeof(EAlignment))));
writer.WriteElementString("Align", Enum.GetName(typeof(EAlignment), Align));
writer.WriteComment("<Style>: Text style: " + CConfig.ListStrings(Enum.GetNames(typeof(EStyle))));
writer.WriteElementString("Style", Enum.GetName(typeof(EStyle), Style));
writer.WriteComment("<Font>: Text font name");
writer.WriteElementString("Font", Fon);
writer.WriteComment("<Text>: Text or translation tag");
if (CLanguage.TranslationExists(Text))
writer.WriteElementString("Text", Text);
else
writer.WriteElementString("Text", string.Empty);
if (!_ButtonText)
{
writer.WriteComment("<Reflection> If exists:");
writer.WriteComment(" <Space>: Reflection Space");
writer.WriteComment(" <Height>: Reflection Height");
}
if (Reflection && !_ButtonText)
{
writer.WriteStartElement("Reflection");
writer.WriteElementString("Space", ReflectionSpace.ToString("#0"));
writer.WriteElementString("Height", ReflectionHeight.ToString("#0"));
writer.WriteEndElement();
}
writer.WriteEndElement();
return true;
}
return false;
}
public void Draw()
{
Draw(false);
}
public void ForceDraw()
{
Draw(true);
}
public void Draw(bool ForceDraw)
{
if (!ForceDraw && !Visible && CSettings.GameState != EGameState.EditTheme)
return;
float h = Height;
float y = Y;
RectangleF bounds = CDraw.GetTextBounds(this);
while (bounds.Width > Bounds.W)
{
h -= 0.2f;
y += 0.1f;
bounds = CDraw.GetTextBounds(this, h);
}
float x = X;
switch (Align)
{
case EAlignment.Center:
x = X - bounds.Width / 2;
break;
case EAlignment.Right:
x = X - bounds.Width;
break;
default:
break;
}
SColorF CurrentColor = new SColorF(Color);
if (Selected)
CurrentColor = new SColorF(SColor);
SColorF color = new SColorF(CurrentColor.R, CurrentColor.G, CurrentColor.B, CurrentColor.A * Alpha);
CFonts.DrawText(CLanguage.Translate(Text), h, x, y, Z, color);
if (Reflection)
{
CFonts.DrawTextReflection(CLanguage.Translate(Text), h, x, y, Z, color, ReflectionSpace, ReflectionHeight);
}
if (Selected && (CSettings.GameState == EGameState.EditTheme))
{
CDraw.DrawColor(new SColorF(0.5f, 1f, 0.5f, 0.5f * CGraphics.GlobalAlpha), new SRectF(x, y, bounds.Width, bounds.Height, Z));
}
CFonts.SetFont("Normal");
CFonts.Style = EStyle.Normal;
}
public void Draw(float begin, float end)
{
RectangleF bounds = CDraw.GetTextBounds(this);
float x = X;
switch (Align)
{
case EAlignment.Center:
x = X - bounds.Width / 2;
break;
case EAlignment.Right:
x = X - bounds.Width;
break;
default:
break;
}
SColorF CurrentColor = new SColorF(Color);
if (Selected)
CurrentColor = new SColorF(SColor);
SColorF color = new SColorF(CurrentColor.R, CurrentColor.G, CurrentColor.B, CurrentColor.A * Alpha);
CFonts.DrawText(Text, Height, x, Y, Z, color, begin, end);
if (Reflection)
{
// TODO
}
if (Selected && (CSettings.GameState == EGameState.EditTheme))
{
CDraw.DrawColor(new SColorF(0.5f, 1f, 0.5f, 0.5f), new SRectF(x, Y, bounds.Width, bounds.Height, Z));
}
CFonts.SetFont("Normal");
CFonts.Style = EStyle.Normal;
}
public void DrawRelative(float x, float y)
{
DrawRelative(x, y, false, 0f, 0f, 0f);
}
public void DrawRelative(float x, float y, float reflectionSpace, float reflectionHeigth, float rectHeight)
{
DrawRelative(x, y, true, reflectionSpace, reflectionHeigth, rectHeight);
}
public void DrawRelative(float rx, float ry, bool reflection, float reflectionSpace, float reflectionHeight, float rectHeight)
{
float h = Height;
float x = X + rx;
float y = Y + ry;
RectangleF bounds = CDraw.GetTextBounds(this);
while (bounds.Width > Bounds.W)
{
h -= 0.2f;
y += 0.1f;
bounds = CDraw.GetTextBounds(this, h);
}
switch (Align)
{
case EAlignment.Center:
x = x - bounds.Width / 2;
break;
case EAlignment.Right:
x = x - bounds.Width;
break;
default:
break;
}
SColorF CurrentColor = new SColorF(Color);
if (Selected)
CurrentColor = new SColorF(SColor);
SColorF color = new SColorF(CurrentColor.R, CurrentColor.G, CurrentColor.B, CurrentColor.A * Alpha);
CFonts.DrawText(CLanguage.Translate(Text), h, x, y, Z, color);
if (reflection)
{
float space = (rectHeight - Y - bounds.Height) * 2f + reflectionSpace;
float height = reflectionHeight - (rectHeight - Y) + bounds.Height;
CFonts.DrawTextReflection(CLanguage.Translate(Text), h, x, y, Z, color, space, height);
}
if (Selected && (CSettings.GameState == EGameState.EditTheme))
{
CDraw.DrawColor(new SColorF(0.5f, 1f, 0.5f, 0.5f * CGraphics.GlobalAlpha), new SRectF(x, y, bounds.Width, bounds.Height, Z));
}
CFonts.SetFont("Normal");
CFonts.Style = EStyle.Normal;
}
public void UnloadTextures()
{
}
public void LoadTextures()
{
if (_Theme.ColorName != String.Empty)
Color = CTheme.GetColor(_Theme.ColorName);
if (_Theme.SColorName != String.Empty)
SColor = CTheme.GetColor(_Theme.SColorName);
}
public void ReloadTextures()
{
UnloadTextures();
LoadTextures();
}
#region ThemeEdit
public void MoveElement(int stepX, int stepY)
{
X += stepX;
Y += stepY;
}
public void ResizeElement(int stepW, int stepH)
{
Height += stepH;
if (Height <= 0)
Height = 1;
}
#endregion ThemeEdit
}
}
+21
View File
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace Vocaluxe.Menu
{
interface IMenuElement
{
bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex);
bool SaveTheme(XmlWriter writer);
void UnloadTextures();
void LoadTextures();
void ReloadTextures();
void MoveElement(int stepX, int stepY);
void ResizeElement(int stepW, int stepH);
}
}
+758
View File
@@ -0,0 +1,758 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Song;
namespace Vocaluxe.Menu.SingNotes
{
struct SPlayerNotes
{
public int ID;
public int PlayerNr;
public SRectF Rect;
public SColorF Color;
public float Alpha;
public CLine[] Lines;
public int LineNr;
public Stopwatch Timer;
public List<CParticleEffect> GoldenStars;
public List<CParticleEffect> Flares;
public List<CParticleEffect> PerfectNoteEffect;
public List<CParticleEffect> PerfectLineTwinkle;
}
struct SThemeSingBar
{
public string Name;
public string SkinLeftName;
public string SkinMiddleName;
public string SkinRightName;
public string SkinBackgroundLeftName;
public string SkinBackgroundMiddleName;
public string SkinBackgroundRightName;
public string SkinGoldenStarName;
public string SkinToneHelperName;
public string SkinPerfectNoteStarName;
}
abstract class CSingNotes : ISingNotes, IMenuElement
{
private SThemeSingBar _Theme;
private bool _ThemeLoaded;
private List<SPlayerNotes> _PlayerNotes;
private int _ActID;
private SRectF[,] _BarPos;
/// <summary>
/// Player bar positions
/// </summary>
/// <remarks>
/// first index = player number; second index = num players seen on screen
/// </remarks>
public SRectF[,] BarPos
{
get { return _BarPos; }
set { _BarPos = value; }
}
public CSingNotes()
{
_Theme = new SThemeSingBar();
_ThemeLoaded = false;
_PlayerNotes = new List<SPlayerNotes>();
_ActID = 0;
}
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
string item = XmlPath + "/" + ElementName;
_ThemeLoaded = true;
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinLeft", navigator, ref _Theme.SkinLeftName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinMiddle", navigator, ref _Theme.SkinMiddleName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinRight", navigator, ref _Theme.SkinRightName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinBackgroundLeft", navigator, ref _Theme.SkinBackgroundLeftName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinBackgroundMiddle", navigator, ref _Theme.SkinBackgroundMiddleName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinBackgroundRight", navigator, ref _Theme.SkinBackgroundRightName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinGoldenStar", navigator, ref _Theme.SkinGoldenStarName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinToneHelper", navigator, ref _Theme.SkinToneHelperName, String.Empty);
_ThemeLoaded &= CHelper.GetValueFromXML(item + "/SkinPerfectNoteStar", navigator, ref _Theme.SkinPerfectNoteStarName, String.Empty);
_BarPos = new SRectF[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer];
for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++)
{
for (int player = 0; player < CSettings.MaxNumPlayer; player++)
{
if (player <= numplayer)
{
_BarPos[player, numplayer] = new SRectF();
string target = "/BarPositions/P" + (player + 1).ToString() + "N" + (numplayer + 1).ToString();
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + target + "X", navigator, ref _BarPos[player, numplayer].X);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + target + "Y", navigator, ref _BarPos[player, numplayer].Y);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + target + "Z", navigator, ref _BarPos[player, numplayer].Z);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + target + "W", navigator, ref _BarPos[player, numplayer].W);
_ThemeLoaded &= CHelper.TryGetFloatValueFromXML(item + target + "H", navigator, ref _BarPos[player, numplayer].H);
}
}
}
if (_ThemeLoaded)
{
_Theme.Name = ElementName;
LoadTextures();
}
return _ThemeLoaded;
}
public bool SaveTheme(XmlWriter writer)
{
if (_ThemeLoaded)
{
writer.WriteStartElement(_Theme.Name);
writer.WriteComment("<SkinLeft>: Texture name of note begin");
writer.WriteElementString("SkinLeft", _Theme.SkinLeftName);
writer.WriteComment("<SkinMiddle>: Texture name of note middle");
writer.WriteElementString("SkinMiddle", _Theme.SkinMiddleName);
writer.WriteComment("<SkinRight>: Texture name of note end");
writer.WriteElementString("SkinRight", _Theme.SkinRightName);
writer.WriteComment("<SkinBackgroundLeft>: Texture name of note background begin");
writer.WriteElementString("SkinBackgroundLeft", _Theme.SkinBackgroundLeftName);
writer.WriteComment("<SkinBackgroundMiddle>: Texture name of note background middle");
writer.WriteElementString("SkinBackgroundMiddle", _Theme.SkinBackgroundMiddleName);
writer.WriteComment("<SkinBackgroundRight>: Texture name of note background right");
writer.WriteElementString("SkinBackgroundRight", _Theme.SkinBackgroundRightName);
writer.WriteComment("<SkinGoldenStar>: Texture name of golden star");
writer.WriteElementString("SkinGoldenStar", _Theme.SkinGoldenStarName);
writer.WriteComment("<SkinToneHelper>: Texture name of tone helper");
writer.WriteElementString("SkinToneHelper", _Theme.SkinToneHelperName);
writer.WriteComment("<SkinPerfectNoteStar>: Texture name of perfect star");
writer.WriteElementString("SkinPerfectNoteStar", _Theme.SkinPerfectNoteStarName);
writer.WriteComment("<BarPositions>");
writer.WriteComment(" <P$N$X>, <P$N$Y>, <P$N$Z>, <P$N$W>, <P$N$H>");
writer.WriteComment(" position, width and height of note bars: first index = player number; second index = num players seen on screen");
writer.WriteStartElement("BarPositions");
for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++)
{
for (int player = 0; player < CSettings.MaxNumPlayer; player++)
{
if (player <= numplayer)
{
string target = "P" + (player + 1).ToString() + "N" + (numplayer + 1).ToString();
writer.WriteElementString(target + "X", _BarPos[player, numplayer].X.ToString("#0"));
writer.WriteElementString(target + "Y", _BarPos[player, numplayer].Y.ToString("#0"));
writer.WriteElementString(target + "Z", _BarPos[player, numplayer].Z.ToString("#0.00"));
writer.WriteElementString(target + "W", _BarPos[player, numplayer].W.ToString("#0"));
writer.WriteElementString(target + "H", _BarPos[player, numplayer].H.ToString("#0"));
}
}
}
writer.WriteEndElement(); //BarPositions
writer.WriteEndElement();
return true;
}
return false;
}
public virtual void Reset()
{
_PlayerNotes.Clear();
_ActID = 0;
}
public virtual int AddPlayer(SRectF Rect, SColorF Color, int PlayerNr)
{
SPlayerNotes notes = new SPlayerNotes();
notes.Rect = Rect;
notes.Color = Color;
notes.Alpha = 1f;
notes.ID = ++_ActID;
notes.Lines = null;
notes.LineNr = -1;
notes.PlayerNr = PlayerNr;
notes.Timer = new Stopwatch();
notes.GoldenStars = new List<CParticleEffect>();
notes.Flares = new List<CParticleEffect>();
notes.PerfectNoteEffect = new List<CParticleEffect>();
notes.PerfectLineTwinkle = new List<CParticleEffect>();
_PlayerNotes.Add(notes);
return notes.ID;
}
public virtual void RemovePlayer(int ID)
{
}
public virtual void AddLine(int ID, CLine[] Line, int LineNr, int Player)
{
if (Line == null)
return;
int n = FindPlayerLine(ID);
if (n == -1)
return;
if (LineNr == _PlayerNotes[n].LineNr)
return;
SPlayerNotes notes = _PlayerNotes[n];
if (Line.Length == 0 || Line.Length <= LineNr)
return;
notes.Lines = Line;
notes.LineNr = LineNr;
notes.GoldenStars.Clear();
notes.Flares.Clear();
notes.PerfectNoteEffect.Clear();
_PlayerNotes.RemoveAt(n);
_PlayerNotes.Add(notes);
}
public virtual void RemoveLine(int ID)
{
}
public virtual void AddNote(int ID, CNote Note)
{
}
public virtual void SetAlpha(int ID, float Alpha)
{
int n = FindPlayerLine(ID);
if (n == -1)
return;
SPlayerNotes pn = _PlayerNotes[n];
pn.Alpha = Alpha;
_PlayerNotes[n] = pn;
}
public virtual float GetAlpha(int ID)
{
int n = FindPlayerLine(ID);
if (n == -1)
return 0f;
return _PlayerNotes[n].Alpha;
}
public virtual void Draw(int ID, int Player)
{
Draw(ID, null, Player);
}
public virtual void Draw(int ID, List<CLine> SingLine, int Player)
{
int n = FindPlayerLine(ID);
if (n == -1)
return;
if (_PlayerNotes[n].LineNr == -1)
return;
if (_PlayerNotes[n].Lines == null)
return;
if (_PlayerNotes[n].Lines.Length <= _PlayerNotes[n].LineNr)
return;
CLine Line = _PlayerNotes[n].Lines[_PlayerNotes[n].LineNr];
if (CConfig.DrawNoteLines == EOffOn.TR_CONFIG_ON)
{
DrawNoteLines(_PlayerNotes[n].Rect, new SColorF(0.5f, 0.5f, 0.5f, 0.5f * _PlayerNotes[n].Alpha));
}
if (Line.NoteCount == 0)
return;
float w = _PlayerNotes[n].Rect.W;
float h = _PlayerNotes[n].Rect.H;
float dh = h / CSettings.NumNoteLines * (2f - (int)CGame.Player[_PlayerNotes[n].PlayerNr].Difficulty) / 4f;
float beats = Line.LastBeat - Line.FirstBeat + 1;
if (beats == 0)
return;
SColorF color = new SColorF(
_PlayerNotes[n].Color.R,
_PlayerNotes[n].Color.G,
_PlayerNotes[n].Color.B,
_PlayerNotes[n].Color.A * _PlayerNotes[n].Alpha);
float BaseLine = Line.BaseLine;
int Nr = 1;
foreach (CNote note in Line.Notes)
{
if (note.NoteType != ENoteType.Freestyle)
{
float width = note.Duration / beats * w;
SRectF rect = new SRectF(
_PlayerNotes[n].Rect.X + (note.StartBeat - Line.FirstBeat) / beats * w,
_PlayerNotes[n].Rect.Y + (CSettings.NumNoteLines - 1 - (note.Tone - BaseLine)/2) / CSettings.NumNoteLines * h - dh,
width,
h / CSettings.NumNoteLines + 2 * dh,
_PlayerNotes[n].Rect.Z
);
DrawNoteBG(rect, color, 1f, _PlayerNotes[n].Timer);
DrawNote(rect, new SColorF(5f, 5f, 5f, 0.7f * _PlayerNotes[n].Alpha), 0.7f);
if (note.NoteType == ENoteType.Golden)
{
AddGoldenNote(rect, n, Nr);
Nr++;
}
}
}
if (CConfig.DrawToneHelper == EOffOn.TR_CONFIG_ON)
{
DrawToneHelper(n, (int)BaseLine, (CGame.MidBeatD - Line.FirstBeat) / beats * w);
}
int i = 0;
while (i < _PlayerNotes[n].PerfectLineTwinkle.Count)
{
_PlayerNotes[n].PerfectLineTwinkle[i].Update();
if (!_PlayerNotes[n].PerfectLineTwinkle[i].IsAlive)
{
_PlayerNotes[n].PerfectLineTwinkle.RemoveAt(i);
}
else
i++;
}
foreach (CParticleEffect perfline in _PlayerNotes[n].PerfectLineTwinkle)
{
perfline.Draw();
}
if (SingLine == null || SingLine.Count == 0 || CGame.Player[Player].CurrentLine == -1 || SingLine.Count <= CGame.Player[Player].CurrentLine)
{
foreach (CParticleEffect stars in _PlayerNotes[n].GoldenStars)
{
stars.Update();
stars.Alpha = _PlayerNotes[n].Alpha;
stars.Draw();
}
return;
}
foreach (CNote note in SingLine[CGame.Player[Player].CurrentLine].Notes)
{
if (note.StartBeat >= Line.FirstBeat && note.EndBeat <= Line.LastBeat)
{
float width = note.Duration / beats * w;
if (note.EndBeat == CGame.ActBeatD)
width -= (1 - (CGame.MidBeatD - CGame.ActBeatD)) / beats * w;
SRectF rect = new SRectF(
_PlayerNotes[n].Rect.X + (note.StartBeat - Line.FirstBeat) / beats * w,
_PlayerNotes[n].Rect.Y + (CSettings.NumNoteLines - 1 - (note.Tone - BaseLine)/2) / CSettings.NumNoteLines * h - dh,
width,
h / CSettings.NumNoteLines + 2 * dh,
_PlayerNotes[n].Rect.Z
);
float f = 0.7f;
if (!note.Hit)
f = 0.4f;
DrawNote(rect, color, f);
if (note.EndBeat >= CGame.ActBeatD && note.Hit && note.NoteType == ENoteType.Golden)
{
AddFlare(rect, n);
}
if (note.Perfect && note.EndBeat < CGame.ActBeatD)
{
AddPerfectNote(rect, n);
note.Perfect = false;
}
}
}
int currentLine = CGame.Player[Player].SingLine.Count - 1;
if (currentLine > 0)
{
if (CGame.Player[Player].SingLine[currentLine - 1].PerfectLine)
{
AddPerfectLine(n);
CGame.Player[Player].SingLine[currentLine - 1].PerfectLine = false;
}
}
i = 0;
while (i < _PlayerNotes[n].Flares.Count)
{
_PlayerNotes[n].Flares[i].Update();
if (!_PlayerNotes[n].Flares[i].IsAlive)
{
_PlayerNotes[n].Flares.RemoveAt(i);
}
else
i++;
}
i = 0;
while (i < _PlayerNotes[n].PerfectNoteEffect.Count)
{
_PlayerNotes[n].PerfectNoteEffect[i].Update();
if (!_PlayerNotes[n].PerfectNoteEffect[i].IsAlive)
{
_PlayerNotes[n].PerfectNoteEffect.RemoveAt(i);
}
else
i++;
}
foreach (CParticleEffect stars in _PlayerNotes[n].GoldenStars)
{
stars.Update();
stars.Alpha = _PlayerNotes[n].Alpha;
stars.Draw();
}
foreach (CParticleEffect flare in _PlayerNotes[n].Flares)
{
flare.Draw();
}
foreach (CParticleEffect perfnote in _PlayerNotes[n].PerfectNoteEffect)
{
perfnote.Draw();
}
}
public void UnloadTextures()
{
}
public void LoadTextures()
{
}
public void ReloadTextures()
{
UnloadTextures();
LoadTextures();
}
private int FindPlayerLine(int ID)
{
if (ID < 0 || ID > _PlayerNotes.Count)
return -1;
int n = -1;
for (int i = 0; i < _PlayerNotes.Count; i++)
{
if (_PlayerNotes[i].ID == ID)
{
n = i;
break;
}
}
return n;
}
private void DrawNote(SRectF Rect, SColorF Color)
{
DrawNote(Rect, Color, 1f);
}
private void DrawNote(SRectF Rect, SColorF Color, float factor)
{
const int spacing = 0;
float d = (1f - factor) / 2 * Rect.H;
float dw = d;
if (2 * dw > Rect.W)
dw = Rect.W / 2;
SRectF r = new SRectF(
Rect.X + dw + spacing,
Rect.Y + d + spacing,
Rect.W - 2 * dw - 2 * spacing,
Rect.H - 2 * d - 2 * spacing,
Rect.Z
);
STexture NoteBegin = CTheme.GetSkinTexture(_Theme.SkinLeftName);
STexture NoteMiddle = CTheme.GetSkinTexture(_Theme.SkinMiddleName);
STexture NoteEnd = CTheme.GetSkinTexture(_Theme.SkinRightName);
float dx = NoteBegin.width * r.H / NoteBegin.height;
if (2 * dx > r.W)
dx = r.W / 2;
CDraw.DrawTexture(NoteBegin, new SRectF(r.X, r.Y, dx, r.H, r.Z), Color);
CDraw.DrawTexture(NoteMiddle, new SRectF(r.X + dx, r.Y, r.W - 2 * dx, r.H, r.Z), Color);
CDraw.DrawTexture(NoteEnd, new SRectF(r.X + r.W - dx, r.Y, dx, r.H, r.Z), Color);
}
private void DrawNoteBG(SRectF Rect, SColorF Color, float factor, Stopwatch Timer)
{
const int spacing = 0;
const float period = 1.5f; //[s]
if (!Timer.IsRunning)
Timer.Start();
if (Timer.ElapsedMilliseconds / 1000f > period)
{
Timer.Reset();
Timer.Start();
}
float alpha = (float)((Math.Cos((Timer.ElapsedMilliseconds / 1000f) / period * Math.PI * 2) + 1) / 2.0) / 2f + 0.5f;
float d = (1f - factor) / 2 * Rect.H;
float dw = d;
if (2 * dw > Rect.W)
dw = Rect.W / 2;
SRectF r = new SRectF(
Rect.X + dw + spacing,
Rect.Y + d + spacing,
Rect.W - 2 * dw - 2 * spacing,
Rect.H - 2 * d - 2 * spacing,
Rect.Z
);
STexture NoteBackgroundBegin = CTheme.GetSkinTexture(_Theme.SkinBackgroundLeftName);
STexture NoteBackgroundMiddle = CTheme.GetSkinTexture(_Theme.SkinBackgroundMiddleName);
STexture NoteBackgroundEnd = CTheme.GetSkinTexture(_Theme.SkinBackgroundRightName);
float dx = NoteBackgroundBegin.width * r.H / NoteBackgroundBegin.height;
if (2 * dx > r.W)
dx = r.W / 2;
SColorF col = new SColorF(Color.R, Color.G, Color.B, Color.A * alpha);
CDraw.DrawTexture(NoteBackgroundBegin, new SRectF(r.X, r.Y, dx, r.H, r.Z), col);
CDraw.DrawTexture(NoteBackgroundMiddle, new SRectF(r.X + dx, r.Y, r.W - 2 * dx, r.H, r.Z), col);
CDraw.DrawTexture(NoteBackgroundEnd, new SRectF(r.X + r.W - dx, r.Y, dx, r.H, r.Z), col);
}
protected void DrawNoteLines(SRectF Rect, SColorF Color)
{
for (int i = 0; i < CSettings.NumNoteLines - 1; i++)
{
float y = Rect.Y + Rect.H / CSettings.NumNoteLines * (i + 1);
CDraw.DrawColor(Color, new SRectF(Rect.X, y, Rect.W, 1, -0.5f));
}
}
private void AddGoldenNote(SRectF Rect, int n, int Nr)
{
AddGoldenNote(Rect, n, Nr, 1f);
}
private void AddGoldenNote(SRectF Rect, int n, int Nr, float factor)
{
const int spacing = 0;
if ( Nr > _PlayerNotes[n].GoldenStars.Count)
{
float d = (1f - factor) / 2 * Rect.H;
float dw = d;
if (2 * dw > Rect.W)
dw = Rect.W / 2;
SRectF r = new SRectF(
Rect.X + dw + spacing,
Rect.Y + d + spacing,
Rect.W - 2 * dw - 2 * spacing,
Rect.H - 2 * d - 2 * spacing,
Rect.Z
);
int numstars = (int)(r.W * 0.25f);
CParticleEffect stars = new CParticleEffect(numstars, new SColorF(1f, 1f, 0f, 1f), r, _Theme.SkinGoldenStarName, 20, EParticeType.Star);
_PlayerNotes[n].GoldenStars.Add(stars);
}
}
private void AddFlare(SRectF Rect, int n)
{
AddFlare(Rect, n, 1f);
}
private void AddFlare(SRectF Rect, int n, float factor)
{
const int spacing = 0;
float d = (1f - factor) / 2 * Rect.H;
float dw = d;
if (2 * dw > Rect.W)
dw = Rect.W / 2;
SRectF r = new SRectF(
Rect.X + dw + spacing + Rect.W - 2 * dw - 2 * spacing,
Rect.Y + d + spacing,
0f,
Rect.H - 2 * d - 2 * spacing,
Rect.Z
);
CParticleEffect flares = new CParticleEffect(15, new SColorF(1f, 1f, 1f, 1f), r, _Theme.SkinGoldenStarName, 20, EParticeType.Flare);
_PlayerNotes[n].Flares.Add(flares);
}
private void AddPerfectNote(SRectF Rect, int n)
{
AddPerfectNote(Rect, n, 1f);
}
private void AddPerfectNote(SRectF Rect, int n, float factor)
{
const int spacing = 0;
float d = (1f - factor) / 2 * Rect.H;
float dw = d;
if (2 * dw > Rect.W)
dw = Rect.W / 2;
SRectF r = new SRectF(
Rect.X + dw + spacing,
Rect.Y + d + spacing,
Rect.W - 2 * dw - 2 * spacing,
Rect.H - 2 * d - 2 * spacing,
Rect.Z
);
STexture NoteBegin = CTheme.GetSkinTexture(_Theme.SkinLeftName);
float dx = NoteBegin.width * r.H / NoteBegin.height;
if (2 * dx > r.W)
dx = r.W / 2;
r = new SRectF(
r.X + r.W - dx,
r.Y,
dx * 0.5f,
dx * 0.2f,
Rect.Z
);
CParticleEffect stars = new CParticleEffect(CGame.Rand.Next(2) + 1, new SColorF(1f, 1f, 1f, 1f), r, _Theme.SkinPerfectNoteStarName, 35, EParticeType.PerfNoteStar);
_PlayerNotes[n].PerfectNoteEffect.Add(stars);
}
private void AddPerfectLine(int n)
{
CParticleEffect twinkle = new CParticleEffect(200, _PlayerNotes[n].Color, _PlayerNotes[n].Rect, _Theme.SkinGoldenStarName, 25, EParticeType.Twinkle);
_PlayerNotes[n].PerfectLineTwinkle.Add(twinkle);
}
private void DrawToneHelper(int n, int BaseLine, float XOffset)
{
int TonePlayer = CSound.RecordGetToneAbs(_PlayerNotes[n].PlayerNr);
SRectF Rect = _PlayerNotes[n].Rect;
while (TonePlayer - BaseLine < 0)
TonePlayer += 12;
while (TonePlayer - BaseLine > 12)
TonePlayer -= 12;
if (XOffset < 0f)
XOffset = 0f;
if (XOffset > Rect.W)
XOffset = Rect.W;
float dy = Rect.H / (CSettings.NumNoteLines);
SRectF rect = new SRectF(
Rect.X - dy + XOffset,
Rect.Y + dy * (CSettings.NumNoteLines - 1 - (TonePlayer - BaseLine) / 2f),
dy,
dy,
Rect.Z
);
SColorF color = new SColorF(
_PlayerNotes[n].Color.R,
_PlayerNotes[n].Color.G,
_PlayerNotes[n].Color.B,
_PlayerNotes[n].Color.A * _PlayerNotes[n].Alpha);
STexture ToneHelper = CTheme.GetSkinTexture(_Theme.SkinToneHelperName);
CDraw.DrawTexture(ToneHelper, rect, color);
while (TonePlayer - BaseLine < 12)
TonePlayer += 12;
while (TonePlayer - BaseLine > 24)
TonePlayer -= 12;
rect = new SRectF(
Rect.X - dy + XOffset,
Rect.Y + dy * (CSettings.NumNoteLines - 1 - (TonePlayer - BaseLine) / 2f),
dy,
dy,
Rect.Z
);
CDraw.DrawTexture(ToneHelper, rect, color);
}
#region ThemeEdit
public void MoveElement(int stepX, int stepY)
{
}
public void ResizeElement(int stepW, int stepH)
{
}
#endregion ThemeEdit
}
}
@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Menu.SingNotes
{
class CSingNotesClassic : CSingNotes
{
}
}
+28
View File
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Text;
using Vocaluxe.Lib.Draw;
using Vocaluxe.Lib.Song;
namespace Vocaluxe.Menu.SingNotes
{
interface ISingNotes
{
void Reset();
int AddPlayer(SRectF Rect, SColorF Color, int PlayerNr);
void RemovePlayer(int ID);
void AddLine(int ID, CLine[] Line, int LineNr, int Player);
void RemoveLine(int ID);
void AddNote(int ID, CNote Note);
void SetAlpha(int ID, float Alpha);
float GetAlpha(int ID);
void Draw(int ID, int Player);
void Draw(int ID, List<CLine> SingLine, int Player);
}
}
+189
View File
@@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Vocaluxe.Base;
using Vocaluxe.Lib.Draw;
namespace Vocaluxe.Menu.SongMenu
{
class CSongMenu : ISongMenu
{
private ISongMenu _SongMenu;
private ESongMenu _Type;
public CSongMenu()
{
CreateSongMenu();
}
public void UpdateSongMenuType()
{
if (_Type != CConfig.SongMenu)
CreateSongMenu();
}
public bool Selected
{
get { return _SongMenu.IsSelected(); }
set { _SongMenu.SetSelected(value); }
}
public bool Visible
{
get { return _SongMenu.IsSelected(); }
set { _SongMenu.SetSelected(value); }
}
public SRectF Rect
{
get { return _SongMenu.GetRect(); }
}
#region ISongMenu
public void Update()
{
_SongMenu.Update();
}
public void OnShow()
{
_SongMenu.OnShow();
}
public void OnHide()
{
_SongMenu.OnHide();
}
public void HandleInput(ref KeyEvent KeyEvent)
{
_SongMenu.HandleInput(ref KeyEvent);
}
public void HandleMouse(ref MouseEvent MouseEvent)
{
_SongMenu.HandleMouse(ref MouseEvent);
}
public void Draw()
{
_SongMenu.Draw();
}
public int GetSelectedSong()
{
return _SongMenu.GetSelectedSong();
}
public void SetSelectedSong(int VisibleSongNr)
{
_SongMenu.SetSelectedSong(VisibleSongNr);
}
public int GetSelectedCategory()
{
return _SongMenu.GetSelectedCategory();
}
public int GetActualSelection()
{
return _SongMenu.GetActualSelection();
}
public bool IsSelected()
{
return _SongMenu.IsSelected();
}
public void SetSelected(bool Selected)
{
_SongMenu.SetSelected(Selected);
}
public bool IsVisible()
{
return _SongMenu.IsVisible();
}
public void SetVisible(bool Visible)
{
_SongMenu.SetVisible(Visible);
}
public SRectF GetRect()
{
return _SongMenu.GetRect();
}
#endregion ISongMenu
#region IMenuElement
public bool LoadTheme(string XmlPath, string ElementName, XPathNavigator navigator, int SkinIndex)
{
return _SongMenu.LoadTheme(XmlPath, ElementName, navigator, SkinIndex);
}
public bool SaveTheme(XmlWriter writer)
{
return _SongMenu.SaveTheme(writer);
}
public void UnloadTextures()
{
_SongMenu.UnloadTextures();
}
public void LoadTextures()
{
_SongMenu.LoadTextures();
}
public void ReloadTextures()
{
_SongMenu.ReloadTextures();
}
public void MoveElement(int stepX, int stepY)
{
_SongMenu.MoveElement(stepX, stepY);
}
public void ResizeElement(int stepW, int stepH)
{
_SongMenu.ResizeElement(stepW, stepH);
}
#endregion IMenuElement
private void CreateSongMenu()
{
if (_SongMenu != null)
{
_SongMenu.OnHide();
}
switch (CConfig.SongMenu)
{
case ESongMenu.TR_CONFIG_LIST:
_SongMenu = new CSongMenuList();
break;
case ESongMenu.TR_CONFIG_DREIDEL:
_SongMenu = new CSongMenuDreidel();
break;
case ESongMenu.TR_CONFIG_TILE_BOARD:
_SongMenu = new CSongMenuTileBoard();
break;
case ESongMenu.TR_CONFIG_BOOK:
_SongMenu = new CSongMenuBook();
break;
}
_Type = CConfig.SongMenu;
}
}
}
+10
View File
@@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Vocaluxe.Menu.SongMenu
{
class CSongMenuBook : CSongMenuFramework
{
}
}
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more