feat: merge data_refactoring into master
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@ -6,3 +6,4 @@ __pycache__/
|
|||||||
.vscode
|
.vscode
|
||||||
cache
|
cache
|
||||||
config
|
config
|
||||||
|
*.code-workspace
|
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
[submodule "libs/replication"]
|
||||||
|
path = libs/replication
|
||||||
|
url = git@gitlab.com:slumber/replication.git
|
674
LICENSE
Normal file
674
LICENSE
Normal 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.
|
||||||
|
|
||||||
|
rcf
|
||||||
|
Copyright (C) 2019 Swann Martinez
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
rcf Copyright (C) 2019 Swann Martinez
|
||||||
|
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>.
|
12
README.md
12
README.md
@ -1,5 +1,5 @@
|
|||||||
# Realtime Collaborative Framework experiments
|
# Multi-user blender addon
|
||||||
> Blender multiuser addon
|
> Enable realtime collaborative workflow inside blender
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|
||||||
@ -8,3 +8,11 @@
|
|||||||
| ZeroMQ | latest | yes |
|
| ZeroMQ | latest | yes |
|
||||||
| umsgpack | latest | yes |
|
| umsgpack | latest | yes |
|
||||||
| PyYAML | latest | yes |
|
| PyYAML | latest | yes |
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
1. Fork it (<https://gitlab.com/yourname/yourproject/fork>)
|
||||||
|
2. Create your feature branch (`git checkout -b feature/fooBar`)
|
||||||
|
3. Commit your changes (`git commit -am 'Add some fooBar'`)
|
||||||
|
4. Push to the branch (`git push origin feature/fooBar`)
|
||||||
|
5. Create a new Pull Request
|
62
__init__.py
62
__init__.py
@ -9,15 +9,13 @@ bl_info = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
import addon_utils
|
|
||||||
import logging
|
import logging
|
||||||
import random
|
import random
|
||||||
import string
|
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
import bpy
|
import bpy
|
||||||
from . import environment
|
from . import environment
|
||||||
from bpy.app.handlers import persistent
|
from . import utils
|
||||||
|
|
||||||
|
|
||||||
DEPENDENCIES = {
|
DEPENDENCIES = {
|
||||||
@ -32,17 +30,17 @@ logger.setLevel(logging.DEBUG)
|
|||||||
|
|
||||||
# UTILITY FUNCTIONS
|
# UTILITY FUNCTIONS
|
||||||
def client_list_callback(scene, context):
|
def client_list_callback(scene, context):
|
||||||
from . import client
|
from . import operators
|
||||||
|
from .bl_types.bl_user import BlUser
|
||||||
|
|
||||||
items = [("Common", "Common", "")]
|
items = [("Common", "Common", "")]
|
||||||
|
|
||||||
username = bpy.context.window_manager.session.username
|
username = bpy.context.window_manager.session.username
|
||||||
|
cli = operators.client
|
||||||
if client.instance:
|
if cli:
|
||||||
client_keys = client.instance.list()
|
client_keys = cli.list(filter=BlUser)
|
||||||
for k in client_keys:
|
for k in client_keys:
|
||||||
if 'Client' in k[0]:
|
name = cli.get(k).buffer["name"]
|
||||||
name = k[1]
|
|
||||||
|
|
||||||
name_desc = name
|
name_desc = name
|
||||||
if name == username:
|
if name == username:
|
||||||
@ -53,12 +51,6 @@ def client_list_callback(scene, context):
|
|||||||
return items
|
return items
|
||||||
|
|
||||||
|
|
||||||
def randomStringDigits(stringLength=6):
|
|
||||||
"""Generate a random string of letters and digits """
|
|
||||||
lettersAndDigits = string.ascii_letters + string.digits
|
|
||||||
return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))
|
|
||||||
|
|
||||||
|
|
||||||
def randomColor():
|
def randomColor():
|
||||||
r = random.random()
|
r = random.random()
|
||||||
v = random.random()
|
v = random.random()
|
||||||
@ -96,7 +88,7 @@ class ReplicatedDatablock(bpy.types.PropertyGroup):
|
|||||||
class SessionProps(bpy.types.PropertyGroup):
|
class SessionProps(bpy.types.PropertyGroup):
|
||||||
username: bpy.props.StringProperty(
|
username: bpy.props.StringProperty(
|
||||||
name="Username",
|
name="Username",
|
||||||
default="user_{}".format(randomStringDigits()),
|
default="user_{}".format(utils.random_string_digits()),
|
||||||
update=save_session_config
|
update=save_session_config
|
||||||
)
|
)
|
||||||
ip: bpy.props.StringProperty(
|
ip: bpy.props.StringProperty(
|
||||||
@ -105,6 +97,10 @@ class SessionProps(bpy.types.PropertyGroup):
|
|||||||
default="127.0.0.1",
|
default="127.0.0.1",
|
||||||
update=save_session_config
|
update=save_session_config
|
||||||
)
|
)
|
||||||
|
user_uuid: bpy.props.StringProperty(
|
||||||
|
name="user_uuid",
|
||||||
|
default="None"
|
||||||
|
)
|
||||||
port: bpy.props.IntProperty(
|
port: bpy.props.IntProperty(
|
||||||
name="port",
|
name="port",
|
||||||
description='Distant host port',
|
description='Distant host port',
|
||||||
@ -115,20 +111,13 @@ class SessionProps(bpy.types.PropertyGroup):
|
|||||||
name="add_property_depth",
|
name="add_property_depth",
|
||||||
default=1
|
default=1
|
||||||
)
|
)
|
||||||
buffer: bpy.props.StringProperty(name="None")
|
outliner_filter: bpy.props.StringProperty(name="None")
|
||||||
is_admin: bpy.props.BoolProperty(name="is_admin", default=False)
|
is_admin: bpy.props.BoolProperty(name="is_admin", default=False)
|
||||||
load_data: bpy.props.BoolProperty(name="load_data", default=True)
|
init_scene: bpy.props.BoolProperty(name="init_scene", default=True)
|
||||||
reset_rights: bpy.props.BoolProperty(name="reset_rights", default=True)
|
|
||||||
init_scene: bpy.props.BoolProperty(name="load_data", default=True)
|
|
||||||
start_empty: bpy.props.BoolProperty(
|
start_empty: bpy.props.BoolProperty(
|
||||||
name="start_empty",
|
name="start_empty",
|
||||||
default=False,
|
default=False,
|
||||||
update=save_session_config
|
update=save_session_config)
|
||||||
)
|
|
||||||
update_frequency: bpy.props.FloatProperty(
|
|
||||||
name="update_frequency",
|
|
||||||
default=0.008
|
|
||||||
)
|
|
||||||
active_object: bpy.props.PointerProperty(
|
active_object: bpy.props.PointerProperty(
|
||||||
name="active_object", type=bpy.types.Object)
|
name="active_object", type=bpy.types.Object)
|
||||||
session_mode: bpy.props.EnumProperty(
|
session_mode: bpy.props.EnumProperty(
|
||||||
@ -146,8 +135,7 @@ class SessionProps(bpy.types.PropertyGroup):
|
|||||||
clients: bpy.props.EnumProperty(
|
clients: bpy.props.EnumProperty(
|
||||||
name="clients",
|
name="clients",
|
||||||
description="client enum",
|
description="client enum",
|
||||||
items=client_list_callback
|
items=client_list_callback)
|
||||||
)
|
|
||||||
enable_presence: bpy.props.BoolProperty(
|
enable_presence: bpy.props.BoolProperty(
|
||||||
name="enable_presence",
|
name="enable_presence",
|
||||||
description='Enable overlay drawing module',
|
description='Enable overlay drawing module',
|
||||||
@ -156,7 +144,6 @@ class SessionProps(bpy.types.PropertyGroup):
|
|||||||
)
|
)
|
||||||
supported_datablock: bpy.props.CollectionProperty(
|
supported_datablock: bpy.props.CollectionProperty(
|
||||||
type=ReplicatedDatablock,
|
type=ReplicatedDatablock,
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def load(self):
|
def load(self):
|
||||||
@ -200,10 +187,11 @@ class SessionProps(bpy.types.PropertyGroup):
|
|||||||
|
|
||||||
classes = (
|
classes = (
|
||||||
ReplicatedDatablock,
|
ReplicatedDatablock,
|
||||||
SessionProps
|
SessionProps,
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
libs = os.path.dirname(os.path.abspath(__file__))+"\\libs\\replication"
|
||||||
|
|
||||||
@persistent
|
@persistent
|
||||||
def load_handler(dummy):
|
def load_handler(dummy):
|
||||||
@ -215,6 +203,10 @@ def load_handler(dummy):
|
|||||||
|
|
||||||
|
|
||||||
def register():
|
def register():
|
||||||
|
if libs not in sys.path:
|
||||||
|
sys.path.append(libs)
|
||||||
|
print(libs)
|
||||||
|
|
||||||
environment.setup(DEPENDENCIES,bpy.app.binary_path_python)
|
environment.setup(DEPENDENCIES,bpy.app.binary_path_python)
|
||||||
|
|
||||||
from . import operators
|
from . import operators
|
||||||
@ -223,13 +215,11 @@ def register():
|
|||||||
for cls in classes:
|
for cls in classes:
|
||||||
bpy.utils.register_class(cls)
|
bpy.utils.register_class(cls)
|
||||||
|
|
||||||
bpy.types.ID.id = bpy.props.StringProperty(default="None")
|
|
||||||
bpy.types.ID.is_dirty = bpy.props.BoolProperty(default=False)
|
|
||||||
bpy.types.WindowManager.session = bpy.props.PointerProperty(
|
bpy.types.WindowManager.session = bpy.props.PointerProperty(
|
||||||
type=SessionProps)
|
type=SessionProps)
|
||||||
|
bpy.types.ID.uuid = bpy.props.StringProperty(default="")
|
||||||
bpy.app.handlers.load_post.append(load_handler)
|
bpy.context.window_manager.session.load()
|
||||||
|
save_session_config(bpy.context.window_manager.session,bpy.context)
|
||||||
operators.register()
|
operators.register()
|
||||||
ui.register()
|
ui.register()
|
||||||
|
|
||||||
@ -242,8 +232,6 @@ def unregister():
|
|||||||
operators.unregister()
|
operators.unregister()
|
||||||
|
|
||||||
del bpy.types.WindowManager.session
|
del bpy.types.WindowManager.session
|
||||||
del bpy.types.ID.id
|
|
||||||
del bpy.types.ID.is_dirty
|
|
||||||
|
|
||||||
for cls in reversed(classes):
|
for cls in reversed(classes):
|
||||||
bpy.utils.unregister_class(cls)
|
bpy.utils.unregister_class(cls)
|
||||||
|
20
bl_types/__init__.py
Normal file
20
bl_types/__init__.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
__all__ = [
|
||||||
|
'bl_user',
|
||||||
|
'bl_object',
|
||||||
|
'bl_mesh',
|
||||||
|
'bl_camera',
|
||||||
|
'bl_collection',
|
||||||
|
'bl_curve',
|
||||||
|
'bl_gpencil',
|
||||||
|
'bl_image',
|
||||||
|
'bl_light',
|
||||||
|
'bl_scene',
|
||||||
|
'bl_material',
|
||||||
|
] # Order here defines execution order
|
||||||
|
|
||||||
|
from . import *
|
||||||
|
from ..libs.replication.data import ReplicatedDataFactory
|
||||||
|
|
||||||
|
def types_to_register():
|
||||||
|
return __all__
|
||||||
|
|
32
bl_types/bl_camera.py
Normal file
32
bl_types/bl_camera.py
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
class BlCamera(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'CAMERA_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
return bpy.data.cameras.new(data["name"])
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
|
||||||
|
return utils.dump_datablock(pointer, 1)
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.cameras.get(self.buffer['name'])
|
||||||
|
|
||||||
|
bl_id = "cameras"
|
||||||
|
bl_class = bpy.types.Camera
|
||||||
|
bl_rep_class = BlCamera
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
60
bl_types/bl_collection.py
Normal file
60
bl_types/bl_collection.py
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
|
||||||
|
class BlCollection(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'FILE_FOLDER'
|
||||||
|
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self,data):
|
||||||
|
return bpy.data.collections.new(data["name"])
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
# Load other meshes metadata
|
||||||
|
# dump_anything.load(target, data)
|
||||||
|
|
||||||
|
# link objects
|
||||||
|
for object in data["objects"]:
|
||||||
|
if object not in target.objects.keys():
|
||||||
|
target.objects.link(bpy.data.objects[object])
|
||||||
|
|
||||||
|
for object in target.objects.keys():
|
||||||
|
if object not in data["objects"]:
|
||||||
|
target.objects.unlink(bpy.data.objects[object])
|
||||||
|
|
||||||
|
# Link childrens
|
||||||
|
for collection in data["children"]:
|
||||||
|
if collection not in target.children.keys():
|
||||||
|
if bpy.data.collections.find(collection) == -1:
|
||||||
|
target.children.link(
|
||||||
|
bpy.data.collections[collection])
|
||||||
|
|
||||||
|
for collection in target.children.keys():
|
||||||
|
if collection not in data["children"]:
|
||||||
|
target.collection.children.unlink(
|
||||||
|
bpy.data.collections[collection])
|
||||||
|
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
return utils.dump_datablock(pointer, 4)
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.collections.get(self.buffer['name'])
|
||||||
|
|
||||||
|
def diff(self):
|
||||||
|
return (len(self.pointer.objects) != len(self.buffer['objects']) or
|
||||||
|
len(self.pointer.children) != len(self.buffer['children']))
|
||||||
|
|
||||||
|
bl_id = "collections"
|
||||||
|
bl_class = bpy.types.Collection
|
||||||
|
bl_rep_class = BlCollection
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
54
bl_types/bl_curve.py
Normal file
54
bl_types/bl_curve.py
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
class BlCurve(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'CURVE_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
return bpy.data.curves.new(data["name"], 'CURVE')
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
target.splines.clear()
|
||||||
|
# load splines
|
||||||
|
for spline in data['splines']:
|
||||||
|
# Update existing..
|
||||||
|
# if spline in target.splines.keys():
|
||||||
|
|
||||||
|
new_spline = target.splines.new(data['splines'][spline]['type'])
|
||||||
|
utils.dump_anything.load(new_spline, data['splines'][spline])
|
||||||
|
|
||||||
|
# Load curve geometry data
|
||||||
|
for bezier_point_index in data['splines'][spline]["bezier_points"]:
|
||||||
|
new_spline.bezier_points.add(1)
|
||||||
|
utils.dump_anything.load(
|
||||||
|
new_spline.bezier_points[bezier_point_index], data['splines'][spline]["bezier_points"][bezier_point_index])
|
||||||
|
|
||||||
|
for point_index in data['splines'][spline]["points"]:
|
||||||
|
new_spline.points.add(1)
|
||||||
|
utils.dump_anything.load(
|
||||||
|
new_spline.points[point_index], data['splines'][spline]["points"][point_index])
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
data = utils.dump_datablock(pointer, 1)
|
||||||
|
utils.dump_datablock_attibutes(
|
||||||
|
pointer, ['splines'], 5, data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.curves.get(self.buffer['name'])
|
||||||
|
|
||||||
|
bl_id = "curves"
|
||||||
|
bl_class = bpy.types.Curve
|
||||||
|
bl_rep_class = BlCurve
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
79
bl_types/bl_gpencil.py
Normal file
79
bl_types/bl_gpencil.py
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
def load_gpencil_layer(target=None, data=None, create=False):
|
||||||
|
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
for frame in data["frames"]:
|
||||||
|
try:
|
||||||
|
tframe = target.frames[frame]
|
||||||
|
except:
|
||||||
|
tframe = target.frames.new(frame)
|
||||||
|
utils.dump_anything.load(tframe, data["frames"][frame])
|
||||||
|
for stroke in data["frames"][frame]["strokes"]:
|
||||||
|
try:
|
||||||
|
tstroke = tframe.strokes[stroke]
|
||||||
|
except:
|
||||||
|
tstroke = tframe.strokes.new()
|
||||||
|
utils.dump_anything.load(
|
||||||
|
tstroke, data["frames"][frame]["strokes"][stroke])
|
||||||
|
|
||||||
|
for point in data["frames"][frame]["strokes"][stroke]["points"]:
|
||||||
|
p = data["frames"][frame]["strokes"][stroke]["points"][point]
|
||||||
|
|
||||||
|
tstroke.points.add(1)
|
||||||
|
tpoint = tstroke.points[len(tstroke.points)-1]
|
||||||
|
|
||||||
|
utils.dump_anything.load(tpoint, p)
|
||||||
|
|
||||||
|
class BlGpencil(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'GREASEPENCIL'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self,data):
|
||||||
|
return bpy.data.grease_pencils.new(data["name"])
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
for layer in target.layers:
|
||||||
|
target.layers.remove(layer)
|
||||||
|
|
||||||
|
if "layers" in data.keys():
|
||||||
|
for layer in data["layers"]:
|
||||||
|
if layer not in target.layers.keys():
|
||||||
|
gp_layer = target.layers.new(data["layers"][layer]["info"])
|
||||||
|
else:
|
||||||
|
gp_layer = target.layers[layer]
|
||||||
|
load_gpencil_layer(
|
||||||
|
target=gp_layer, data=data["layers"][layer], create=create)
|
||||||
|
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
target.materials.clear()
|
||||||
|
if "materials" in data.keys():
|
||||||
|
for mat in data['materials']:
|
||||||
|
target.materials.append(bpy.data.materials[mat])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
data = utils.dump_datablock(pointer, 2)
|
||||||
|
utils.dump_datablock_attibutes(
|
||||||
|
pointer, ['layers'], 9, data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.grease_pencils.get(self.buffer['name'])
|
||||||
|
|
||||||
|
bl_id = "grease_pencils"
|
||||||
|
bl_class = bpy.types.GreasePencil
|
||||||
|
bl_rep_class = BlGpencil
|
||||||
|
bl_delay_refresh = 5
|
||||||
|
bl_delay_apply = 5
|
73
bl_types/bl_image.py
Normal file
73
bl_types/bl_image.py
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
import os
|
||||||
|
|
||||||
|
from .. import utils, environment
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
def dump_image(image):
|
||||||
|
pixels = None
|
||||||
|
if image.source == "GENERATED":
|
||||||
|
img_name = "{}.png".format(image.name)
|
||||||
|
|
||||||
|
image.filepath_raw = os.path.join(environment.CACHE_DIR, img_name)
|
||||||
|
image.file_format = "PNG"
|
||||||
|
image.save()
|
||||||
|
|
||||||
|
if image.source == "FILE":
|
||||||
|
image.save()
|
||||||
|
file = open(image.filepath_raw, "rb")
|
||||||
|
pixels = file.read()
|
||||||
|
else:
|
||||||
|
print("Image format not supported ")
|
||||||
|
return pixels
|
||||||
|
|
||||||
|
class BlImage(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'IMAGE_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
return bpy.data.images.new(
|
||||||
|
name=data['name'],
|
||||||
|
width=data['size'][0],
|
||||||
|
height=data['size'][1]
|
||||||
|
)
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
image = target
|
||||||
|
|
||||||
|
img_name = "{}.png".format(image.name)
|
||||||
|
|
||||||
|
img_path = os.path.join(environment.CACHE_DIR, img_name)
|
||||||
|
|
||||||
|
file = open(img_path, 'wb')
|
||||||
|
file.write(data["pixels"])
|
||||||
|
file.close()
|
||||||
|
|
||||||
|
image.source = 'FILE'
|
||||||
|
image.filepath = img_path
|
||||||
|
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
data = {}
|
||||||
|
data['pixels'] = dump_image(pointer)
|
||||||
|
utils.dump_datablock_attibutes(pointer, [], 2, data)
|
||||||
|
data = utils.dump_datablock_attibutes(
|
||||||
|
pointer,
|
||||||
|
["name", 'size', 'height', 'alpha', 'float_buffer', 'filepath', 'source'],
|
||||||
|
2,
|
||||||
|
data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.images.get(self.buffer['name'])
|
||||||
|
|
||||||
|
bl_id = "images"
|
||||||
|
bl_class = bpy.types.Image
|
||||||
|
bl_rep_class = BlImage
|
||||||
|
bl_delay_refresh = 0
|
||||||
|
bl_delay_apply = 0
|
33
bl_types/bl_light.py
Normal file
33
bl_types/bl_light.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
class BlLight(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'LIGHT_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
return bpy.data.lights.new(data["name"], data["type"])
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
|
||||||
|
return utils.dump_datablock(pointer, 3)
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.lights.get(self.buffer['name'])
|
||||||
|
|
||||||
|
bl_id = "lights"
|
||||||
|
bl_class = bpy.types.Light
|
||||||
|
bl_rep_class = BlLight
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
89
bl_types/bl_material.py
Normal file
89
bl_types/bl_material.py
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
class BlMaterial(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'MATERIAL_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
return bpy.data.materials.new(data["name"])
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
if data['is_grease_pencil']:
|
||||||
|
if not target.is_grease_pencil:
|
||||||
|
bpy.data.materials.create_gpencil_data(target)
|
||||||
|
|
||||||
|
utils.dump_anything.load(target.grease_pencil, data['grease_pencil'])
|
||||||
|
|
||||||
|
utils.load_dict(data['grease_pencil'], target.grease_pencil)
|
||||||
|
|
||||||
|
elif data["use_nodes"]:
|
||||||
|
if target.node_tree is None:
|
||||||
|
target.use_nodes = True
|
||||||
|
|
||||||
|
target.node_tree.nodes.clear()
|
||||||
|
|
||||||
|
for node in data["node_tree"]["nodes"]:
|
||||||
|
# fix None node tree error
|
||||||
|
|
||||||
|
index = target.node_tree.nodes.find(node)
|
||||||
|
|
||||||
|
if index is -1:
|
||||||
|
node_type = data["node_tree"]["nodes"][node]["bl_idname"]
|
||||||
|
|
||||||
|
target.node_tree.nodes.new(type=node_type)
|
||||||
|
|
||||||
|
utils.dump_anything.load(
|
||||||
|
target.node_tree.nodes[index], data["node_tree"]["nodes"][node])
|
||||||
|
|
||||||
|
if data["node_tree"]["nodes"][node]['type'] == 'TEX_IMAGE':
|
||||||
|
target.node_tree.nodes[index].image = bpy.data.images[data["node_tree"]
|
||||||
|
["nodes"][node]['image']['name']]
|
||||||
|
|
||||||
|
for input in data["node_tree"]["nodes"][node]["inputs"]:
|
||||||
|
|
||||||
|
try:
|
||||||
|
if hasattr(target.node_tree.nodes[index].inputs[input], "default_value"):
|
||||||
|
target.node_tree.nodes[index].inputs[input].default_value = data[
|
||||||
|
"node_tree"]["nodes"][node]["inputs"][input]["default_value"]
|
||||||
|
except Exception as e:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Load nodes links
|
||||||
|
target.node_tree.links.clear()
|
||||||
|
|
||||||
|
for link in data["node_tree"]["links"]:
|
||||||
|
current_link = data["node_tree"]["links"][link]
|
||||||
|
input_socket = target.node_tree.nodes[current_link['to_node']
|
||||||
|
['name']].inputs[current_link['to_socket']['name']]
|
||||||
|
output_socket = target.node_tree.nodes[current_link['from_node']
|
||||||
|
['name']].outputs[current_link['from_socket']['name']]
|
||||||
|
|
||||||
|
target.node_tree.links.new(input_socket, output_socket)
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
data = utils.dump_datablock(pointer, 2)
|
||||||
|
if pointer.node_tree:
|
||||||
|
utils.dump_datablock_attibutes(
|
||||||
|
pointer.node_tree, ["nodes", "links"], 5, data['node_tree'])
|
||||||
|
elif pointer.grease_pencil:
|
||||||
|
utils.dump_datablock_attibutes(pointer, ["grease_pencil"], 3, data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.materials.get(self.buffer['name'])
|
||||||
|
|
||||||
|
def diff(self):
|
||||||
|
return len(self.pointer.node_tree.links) != len(self.buffer['node_tree']['links'])
|
||||||
|
bl_id = "materials"
|
||||||
|
bl_class = bpy.types.Material
|
||||||
|
bl_rep_class = BlMaterial
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
173
bl_types/bl_mesh.py
Normal file
173
bl_types/bl_mesh.py
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
import bpy
|
||||||
|
import bmesh
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
def dump_mesh(mesh, data={}):
|
||||||
|
import bmesh
|
||||||
|
|
||||||
|
mesh_data = data
|
||||||
|
mesh_buffer = bmesh.new()
|
||||||
|
|
||||||
|
mesh_buffer.from_mesh(mesh)
|
||||||
|
|
||||||
|
uv_layer = mesh_buffer.loops.layers.uv.verify()
|
||||||
|
bevel_layer = mesh_buffer.verts.layers.bevel_weight.verify()
|
||||||
|
skin_layer = mesh_buffer.verts.layers.skin.verify()
|
||||||
|
|
||||||
|
verts = {}
|
||||||
|
for vert in mesh_buffer.verts:
|
||||||
|
v = {}
|
||||||
|
v["co"] = list(vert.co)
|
||||||
|
|
||||||
|
# vert metadata
|
||||||
|
v['bevel'] = vert[bevel_layer]
|
||||||
|
# v['skin'] = list(vert[skin_layer])
|
||||||
|
|
||||||
|
verts[str(vert.index)] = v
|
||||||
|
|
||||||
|
mesh_data["verts"] = verts
|
||||||
|
|
||||||
|
edges = {}
|
||||||
|
for edge in mesh_buffer.edges:
|
||||||
|
e = {}
|
||||||
|
e["verts"] = [edge.verts[0].index, edge.verts[1].index]
|
||||||
|
|
||||||
|
# Edge metadata
|
||||||
|
e["smooth"] = edge.smooth
|
||||||
|
|
||||||
|
edges[edge.index] = e
|
||||||
|
mesh_data["edges"] = edges
|
||||||
|
|
||||||
|
faces = {}
|
||||||
|
for face in mesh_buffer.faces:
|
||||||
|
f = {}
|
||||||
|
fverts = []
|
||||||
|
for vert in face.verts:
|
||||||
|
fverts.append(vert.index)
|
||||||
|
|
||||||
|
f["verts"] = fverts
|
||||||
|
f["material_index"] = face.material_index
|
||||||
|
|
||||||
|
uvs = []
|
||||||
|
# Face metadata
|
||||||
|
for loop in face.loops:
|
||||||
|
loop_uv = loop[uv_layer]
|
||||||
|
|
||||||
|
uvs.append(list(loop_uv.uv))
|
||||||
|
|
||||||
|
f["uv"] = uvs
|
||||||
|
faces[face.index] = f
|
||||||
|
|
||||||
|
mesh_data["faces"] = faces
|
||||||
|
|
||||||
|
uv_layers = []
|
||||||
|
for uv_layer in mesh.uv_layers:
|
||||||
|
uv_layers.append(uv_layer.name)
|
||||||
|
|
||||||
|
mesh_data["uv_layers"] = uv_layers
|
||||||
|
return mesh_data
|
||||||
|
|
||||||
|
class BlMesh(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'MESH_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
return bpy.data.meshes.new(data["name"])
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
if not target or not target.is_editmode:
|
||||||
|
# 1 - LOAD GEOMETRY
|
||||||
|
mesh_buffer = bmesh.new()
|
||||||
|
|
||||||
|
for i in data["verts"]:
|
||||||
|
v = mesh_buffer.verts.new(data["verts"][i]["co"])
|
||||||
|
|
||||||
|
mesh_buffer.verts.ensure_lookup_table()
|
||||||
|
|
||||||
|
for i in data["edges"]:
|
||||||
|
verts = mesh_buffer.verts
|
||||||
|
v1 = data["edges"][i]["verts"][0]
|
||||||
|
v2 = data["edges"][i]["verts"][1]
|
||||||
|
mesh_buffer.edges.new([verts[v1], verts[v2]])
|
||||||
|
|
||||||
|
for p in data["faces"]:
|
||||||
|
verts = []
|
||||||
|
for v in data["faces"][p]["verts"]:
|
||||||
|
verts.append(mesh_buffer.verts[v])
|
||||||
|
|
||||||
|
if len(verts) > 0:
|
||||||
|
f = mesh_buffer.faces.new(verts)
|
||||||
|
|
||||||
|
uv_layer = mesh_buffer.loops.layers.uv.verify()
|
||||||
|
|
||||||
|
f.material_index = data["faces"][p]['material_index']
|
||||||
|
|
||||||
|
# UV loading
|
||||||
|
for i, loop in enumerate(f.loops):
|
||||||
|
loop_uv = loop[uv_layer]
|
||||||
|
loop_uv.uv = data["faces"][p]["uv"][i]
|
||||||
|
|
||||||
|
|
||||||
|
mesh_buffer.to_mesh(target)
|
||||||
|
|
||||||
|
# mesh_buffer.from_mesh(target)
|
||||||
|
|
||||||
|
# 2 - LOAD METADATA
|
||||||
|
|
||||||
|
# uv's
|
||||||
|
for uv_layer in data['uv_layers']:
|
||||||
|
target.uv_layers.new(name=uv_layer)
|
||||||
|
|
||||||
|
bevel_layer = mesh_buffer.verts.layers.bevel_weight.verify()
|
||||||
|
skin_layer = mesh_buffer.verts.layers.skin.verify()
|
||||||
|
|
||||||
|
# for face in mesh_buffer.faces:
|
||||||
|
|
||||||
|
# # Face metadata
|
||||||
|
# for loop in face.loops:
|
||||||
|
# loop_uv = loop[uv_layer]
|
||||||
|
# loop_uv.uv = data['faces'][face.index]["uv"]
|
||||||
|
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
# 3 - LOAD MATERIAL SLOTS
|
||||||
|
material_to_load = []
|
||||||
|
material_to_load = utils.revers(data["materials"])
|
||||||
|
target.materials.clear()
|
||||||
|
# SLots
|
||||||
|
i = 0
|
||||||
|
|
||||||
|
for m in data["material_list"]:
|
||||||
|
target.materials.append(bpy.data.materials[m])
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
|
||||||
|
data = utils.dump_datablock(pointer, 2)
|
||||||
|
data = dump_mesh(pointer, data)
|
||||||
|
# Fix material index
|
||||||
|
m_list = []
|
||||||
|
for m in pointer.materials:
|
||||||
|
m_list.append(m.name)
|
||||||
|
|
||||||
|
data['material_list'] = m_list
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
self.pointer = bpy.data.meshes.get(self.buffer['name'])
|
||||||
|
|
||||||
|
def diff(self):
|
||||||
|
return len(self.pointer.vertices) != len(self.buffer['verts'])
|
||||||
|
|
||||||
|
bl_id = "meshes"
|
||||||
|
bl_class = bpy.types.Mesh
|
||||||
|
bl_rep_class = BlMesh
|
||||||
|
bl_delay_refresh = 10
|
||||||
|
bl_delay_apply = 10
|
76
bl_types/bl_object.py
Normal file
76
bl_types/bl_object.py
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
class BlObject(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'OBJECT_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
pointer = None
|
||||||
|
|
||||||
|
# Object specific constructor...
|
||||||
|
if data["data"] in bpy.data.meshes.keys():
|
||||||
|
pointer = bpy.data.meshes[data["data"]]
|
||||||
|
elif data["data"] in bpy.data.lights.keys():
|
||||||
|
pointer = bpy.data.lights[data["data"]]
|
||||||
|
elif data["data"] in bpy.data.cameras.keys():
|
||||||
|
pointer = bpy.data.cameras[data["data"]]
|
||||||
|
elif data["data"] in bpy.data.curves.keys():
|
||||||
|
pointer = bpy.data.curves[data["data"]]
|
||||||
|
elif data["data"] in bpy.data.armatures.keys():
|
||||||
|
pointer = bpy.data.armatures[data["data"]]
|
||||||
|
elif data["data"] in bpy.data.grease_pencils.keys():
|
||||||
|
pointer = bpy.data.grease_pencils[data["data"]]
|
||||||
|
elif data["data"] in bpy.data.curves.keys():
|
||||||
|
pointer = bpy.data.curves[data["data"]]
|
||||||
|
|
||||||
|
return bpy.data.objects.new(data["name"], pointer)
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
# Load other meshes metadata
|
||||||
|
# dump_anything.load(target, data)
|
||||||
|
|
||||||
|
target.matrix_world = mathutils.Matrix(data["matrix_world"])
|
||||||
|
|
||||||
|
# Load modifiers
|
||||||
|
if hasattr(target,'modifiers'):
|
||||||
|
for local_modifier in target.modifiers:
|
||||||
|
if local_modifier.name not in data['modifiers']:
|
||||||
|
target.modifiers.remove(local_modifier)
|
||||||
|
for modifier in data['modifiers']:
|
||||||
|
target_modifier = target.modifiers.get(modifier)
|
||||||
|
|
||||||
|
if not target_modifier:
|
||||||
|
target_modifier = target.modifiers.new(data['modifiers'][modifier]['name'],data['modifiers'][modifier]['type'])
|
||||||
|
|
||||||
|
utils.dump_anything.load(target_modifier, data['modifiers'][modifier])
|
||||||
|
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
data = utils.dump_datablock(pointer, 1)
|
||||||
|
|
||||||
|
if hasattr(pointer,'modifiers'):
|
||||||
|
utils.dump_datablock_attibutes(
|
||||||
|
pointer, ['modifiers'], 3, data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
object_name = self.buffer['name']
|
||||||
|
|
||||||
|
self.pointer = bpy.data.objects.get(object_name)
|
||||||
|
|
||||||
|
def diff(self):
|
||||||
|
return self.dump(pointer=self.pointer)['location'] != self.buffer['location']
|
||||||
|
|
||||||
|
bl_id = "objects"
|
||||||
|
bl_class = bpy.types.Object
|
||||||
|
bl_rep_class = BlObject
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
66
bl_types/bl_scene.py
Normal file
66
bl_types/bl_scene.py
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
|
||||||
|
class BlScene(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
self.icon = 'SCENE_DATA'
|
||||||
|
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
def construct(self, data):
|
||||||
|
return bpy.data.scenes.new(data["name"])
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
target = self.pointer
|
||||||
|
# Load other meshes metadata
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
# Load master collection
|
||||||
|
for object in data["collection"]["objects"]:
|
||||||
|
if object not in target.collection.objects.keys():
|
||||||
|
target.collection.objects.link(bpy.data.objects[object])
|
||||||
|
|
||||||
|
for object in target.collection.objects.keys():
|
||||||
|
if object not in data["collection"]["objects"]:
|
||||||
|
target.collection.objects.unlink(bpy.data.objects[object])
|
||||||
|
|
||||||
|
# load collections
|
||||||
|
# TODO: Recursive link
|
||||||
|
for collection in data["collection"]["children"]:
|
||||||
|
if collection not in target.collection.children.keys():
|
||||||
|
target.collection.children.link(
|
||||||
|
bpy.data.collections[collection])
|
||||||
|
|
||||||
|
for collection in target.collection.children.keys():
|
||||||
|
if collection not in data["collection"]["children"]:
|
||||||
|
target.collection.children.unlink(
|
||||||
|
bpy.data.collections[collection])
|
||||||
|
|
||||||
|
def dump(self, pointer=None):
|
||||||
|
assert(pointer)
|
||||||
|
|
||||||
|
data = utils.dump_datablock_attibutes(
|
||||||
|
pointer, ['name', 'collection', 'id', 'camera', 'grease_pencil'], 2)
|
||||||
|
utils.dump_datablock_attibutes(
|
||||||
|
pointer, ['collection'], 4, data)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
def resolve(self):
|
||||||
|
assert(self.buffer)
|
||||||
|
scene_name = self.buffer['name']
|
||||||
|
|
||||||
|
self.pointer = bpy.data.scenes.get(scene_name)
|
||||||
|
|
||||||
|
def diff(self):
|
||||||
|
return (len(self.pointer.collection.objects) != len(self.buffer['collection']['objects']) or
|
||||||
|
len(self.pointer.collection.children) != len(self.buffer['collection']['children']))
|
||||||
|
|
||||||
|
bl_id = "scenes"
|
||||||
|
bl_class = bpy.types.Scene
|
||||||
|
bl_rep_class = BlScene
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
58
bl_types/bl_user.py
Normal file
58
bl_types/bl_user.py
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from .. import utils
|
||||||
|
from .. import presence
|
||||||
|
from ..libs.replication.data import ReplicatedDatablock
|
||||||
|
from ..libs.replication.constants import UP
|
||||||
|
from ..libs.debug import draw_point
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class BlUser(ReplicatedDatablock):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__( *args, **kwargs)
|
||||||
|
|
||||||
|
self.icon = 'CON_ARMATURE'
|
||||||
|
|
||||||
|
if self.buffer:
|
||||||
|
self.load(self.buffer, self.pointer)
|
||||||
|
def construct(self, name):
|
||||||
|
return presence.User()
|
||||||
|
|
||||||
|
def load(self, data, target):
|
||||||
|
target.name = data['name']
|
||||||
|
target.location = data['location']
|
||||||
|
utils.dump_anything.load(target, data)
|
||||||
|
|
||||||
|
def apply(self):
|
||||||
|
if self.pointer is None:
|
||||||
|
self.pointer = self.construct(self.buffer)
|
||||||
|
|
||||||
|
if self.pointer:
|
||||||
|
self.load(data=self.buffer, target=self.pointer)
|
||||||
|
|
||||||
|
self.state = UP
|
||||||
|
#TODO: refactor in order to redraw in cleaner ways
|
||||||
|
if presence.renderer:
|
||||||
|
presence.renderer.draw_client_camera(self.buffer['name'], self.buffer['location'],self.buffer['color'])
|
||||||
|
|
||||||
|
|
||||||
|
def dump(self,pointer=None):
|
||||||
|
data = utils.dump_anything.dump(pointer)
|
||||||
|
data['location'] = pointer.location
|
||||||
|
data['color'] = pointer.color
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def diff(self):
|
||||||
|
for i,coord in enumerate(self.pointer.location):
|
||||||
|
if coord != self.buffer['location'][i]:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
bl_id = "users"
|
||||||
|
bl_class = presence.User
|
||||||
|
bl_rep_class = BlUser
|
||||||
|
bl_delay_refresh = 1
|
||||||
|
bl_delay_apply = 1
|
495
client.py
495
client.py
@ -1,495 +0,0 @@
|
|||||||
import binascii
|
|
||||||
import collections
|
|
||||||
import copy
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
import queue
|
|
||||||
import sys
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from enum import Enum
|
|
||||||
from random import randint
|
|
||||||
import zmq
|
|
||||||
import json
|
|
||||||
|
|
||||||
from . import environment, helpers, message
|
|
||||||
from .libs import dump_anything, umsgpack
|
|
||||||
|
|
||||||
CONNECT_TIMEOUT = 2
|
|
||||||
WATCH_FREQUENCY = 0.1
|
|
||||||
WAITING_TIME = 0.001
|
|
||||||
SERVER_MAX = 1
|
|
||||||
DUMP_AGENTS_NUMBER = 1
|
|
||||||
|
|
||||||
lock = threading.Lock()
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
logger.setLevel(logging.DEBUG)
|
|
||||||
|
|
||||||
instance = None
|
|
||||||
|
|
||||||
|
|
||||||
class State(Enum):
|
|
||||||
INITIAL = 1
|
|
||||||
SYNCING = 2
|
|
||||||
ACTIVE = 3
|
|
||||||
WORKING = 4
|
|
||||||
|
|
||||||
|
|
||||||
def zpipe(ctx):
|
|
||||||
"""build inproc pipe for talking to threads
|
|
||||||
|
|
||||||
mimic pipe used in czmq zthread_fork.
|
|
||||||
|
|
||||||
Returns a pair of PAIRs connected via inproc
|
|
||||||
"""
|
|
||||||
a = ctx.socket(zmq.PAIR)
|
|
||||||
b = ctx.socket(zmq.PAIR)
|
|
||||||
a.linger = b.linger = 0
|
|
||||||
a.hwm = b.hwm = 1
|
|
||||||
iface = "inproc://%s" % binascii.hexlify(os.urandom(8))
|
|
||||||
a.bind(iface)
|
|
||||||
b.connect(iface)
|
|
||||||
return a, b
|
|
||||||
|
|
||||||
|
|
||||||
class Client(object):
|
|
||||||
|
|
||||||
ctx = None
|
|
||||||
pipe = None
|
|
||||||
net_agent = None
|
|
||||||
store = None
|
|
||||||
active_tasks = None
|
|
||||||
|
|
||||||
def __init__(self, executor):
|
|
||||||
self.ctx = zmq.Context()
|
|
||||||
self.pipe, peer = zpipe(self.ctx)
|
|
||||||
self.store = {}
|
|
||||||
self.serial_product = queue.Queue()
|
|
||||||
self.serial_feed = queue.Queue()
|
|
||||||
self.stop_event = threading.Event()
|
|
||||||
self.external_tasks = executor
|
|
||||||
|
|
||||||
# Net agent
|
|
||||||
self.net_agent = threading.Thread(
|
|
||||||
target=net_worker,
|
|
||||||
args=(self.ctx, self.store, peer, self.serial_product, self.serial_feed, self.stop_event,self.external_tasks), name="net-agent")
|
|
||||||
self.net_agent.daemon = True
|
|
||||||
self.net_agent.start()
|
|
||||||
|
|
||||||
# Local data translation agent
|
|
||||||
self.serial_agents = []
|
|
||||||
for a in range(0, DUMP_AGENTS_NUMBER):
|
|
||||||
serial_agent = threading.Thread(
|
|
||||||
target=serial_worker, args=(self.serial_product, self.serial_feed), name="serial-agent")
|
|
||||||
serial_agent.daemon = True
|
|
||||||
serial_agent.start()
|
|
||||||
self.serial_agents.append(serial_agent)
|
|
||||||
|
|
||||||
# Sync agent
|
|
||||||
self.watchdog_agent = threading.Thread(
|
|
||||||
target=watchdog_worker, args=(self.serial_feed,WATCH_FREQUENCY, self.stop_event), name="watchdog-agent")
|
|
||||||
self.watchdog_agent.daemon = True
|
|
||||||
self.watchdog_agent.start()
|
|
||||||
|
|
||||||
# Status
|
|
||||||
self.active_tasks = 0
|
|
||||||
|
|
||||||
def connect(self, id, address, port):
|
|
||||||
self.pipe.send_multipart([b"CONNECT", (id.encode() if isinstance(
|
|
||||||
id, str) else id), (address.encode() if isinstance(
|
|
||||||
address, str) else address), b'%d' % port])
|
|
||||||
|
|
||||||
def init(self):
|
|
||||||
"""
|
|
||||||
Scene initialisation
|
|
||||||
"""
|
|
||||||
self.pipe.send_multipart(
|
|
||||||
[b"INIT"])
|
|
||||||
|
|
||||||
def disconnect(self):
|
|
||||||
"""
|
|
||||||
Disconnect
|
|
||||||
"""
|
|
||||||
self.pipe.send_multipart(
|
|
||||||
[b"DISCONNECT"])
|
|
||||||
|
|
||||||
def set(self, key, value=None, override=False, id=False):
|
|
||||||
"""Set new value in distributed hash table
|
|
||||||
Sends [SET][key][value] to the agent
|
|
||||||
"""
|
|
||||||
|
|
||||||
if value:
|
|
||||||
key = umsgpack.packb(key)
|
|
||||||
value = umsgpack.packb(value) if value else umsgpack.packb('None')
|
|
||||||
override = umsgpack.packb(override)
|
|
||||||
|
|
||||||
self.pipe.send_multipart(
|
|
||||||
[b"SET", key, value, override])
|
|
||||||
else:
|
|
||||||
self.serial_feed.put(('DUMP', key, None, id))
|
|
||||||
|
|
||||||
def add(self, key, value=None):
|
|
||||||
"""Set new value in distributed hash table
|
|
||||||
Sends [SET][key][value] to the agent
|
|
||||||
"""
|
|
||||||
self.serial_feed.put(key)
|
|
||||||
|
|
||||||
def is_busy(self):
|
|
||||||
self.active_tasks = self.serial_feed.qsize() + self.serial_product.qsize()
|
|
||||||
if self.active_tasks == 0:
|
|
||||||
return False
|
|
||||||
else:
|
|
||||||
return True
|
|
||||||
|
|
||||||
def exit(self):
|
|
||||||
if self.net_agent.is_alive():
|
|
||||||
self.disconnect()
|
|
||||||
|
|
||||||
self.stop_event.set()
|
|
||||||
|
|
||||||
for a in range(0, DUMP_AGENTS_NUMBER):
|
|
||||||
self.serial_feed.put(('STOP', None, None,None))
|
|
||||||
|
|
||||||
# READ-ONLY FUNCTIONS
|
|
||||||
def get(self, key):
|
|
||||||
"""Lookup value in distributed hash table
|
|
||||||
Sends [GET][key] to the agent and waits for a value response
|
|
||||||
If there is no clone available, will eventually return None.
|
|
||||||
"""
|
|
||||||
value = []
|
|
||||||
|
|
||||||
for k in self.store.keys():
|
|
||||||
if key in k:
|
|
||||||
value.append([k, self.store.get(k).body])
|
|
||||||
|
|
||||||
return value
|
|
||||||
|
|
||||||
def exist(self, key):
|
|
||||||
"""
|
|
||||||
Fast key exist check
|
|
||||||
"""
|
|
||||||
|
|
||||||
if key in self.store.keys():
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def list(self):
|
|
||||||
dump_list = []
|
|
||||||
for k, v in self.store.items():
|
|
||||||
if 'Client' in k:
|
|
||||||
dump_list.append([k, v.id.decode()])
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
dump_list.append([k, v.body['id']])
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return dump_list
|
|
||||||
|
|
||||||
def state(self):
|
|
||||||
if self.net_agent is None or not self.net_agent.is_alive():
|
|
||||||
return 1 #State.INITIAL
|
|
||||||
elif self.net_agent.is_alive() and self.store.keys():
|
|
||||||
return 3 # State.ACTIVE
|
|
||||||
else:
|
|
||||||
return 2 #State.SYNCING
|
|
||||||
|
|
||||||
|
|
||||||
# SAVING FUNCTIONS
|
|
||||||
def dump(self, filepath):
|
|
||||||
with open('dump.json',"w") as fp:
|
|
||||||
for key, value in self.store.items():
|
|
||||||
line = json.dumps(value.body)
|
|
||||||
fp.write(line)
|
|
||||||
|
|
||||||
|
|
||||||
class Server(object):
|
|
||||||
address = None # Server address
|
|
||||||
port = None # Server port
|
|
||||||
snapshot = None # Snapshot socket
|
|
||||||
subscriber = None # Incoming updates
|
|
||||||
|
|
||||||
def __init__(self, ctx, address, port, id):
|
|
||||||
self.address = address
|
|
||||||
self.port = port
|
|
||||||
self.snapshot = ctx.socket(zmq.DEALER)
|
|
||||||
self.snapshot.linger = 0
|
|
||||||
self.snapshot.setsockopt(zmq.IDENTITY, id)
|
|
||||||
self.snapshot.connect("tcp://{}:{}".format(address.decode(), port))
|
|
||||||
self.subscriber = ctx.socket(zmq.SUB)
|
|
||||||
self.subscriber.setsockopt_string(zmq.SUBSCRIBE, '')
|
|
||||||
self.subscriber.connect("tcp://{}:{}".format(address.decode(), port+1))
|
|
||||||
self.subscriber.linger = 0
|
|
||||||
print("connected on tcp://{}:{}".format(address.decode(), port))
|
|
||||||
|
|
||||||
|
|
||||||
class ClientAgent(object):
|
|
||||||
ctx = None
|
|
||||||
pipe = None
|
|
||||||
property_map = None
|
|
||||||
publisher = None
|
|
||||||
id = None
|
|
||||||
state = None
|
|
||||||
server = None
|
|
||||||
serial = None
|
|
||||||
serialisation_agent = None
|
|
||||||
|
|
||||||
def __init__(self, ctx, store, pipe):
|
|
||||||
self.ctx = ctx
|
|
||||||
self.pipe = pipe
|
|
||||||
self.property_map = store
|
|
||||||
self.id = b"test"
|
|
||||||
self.state = State.INITIAL
|
|
||||||
self.admin = False
|
|
||||||
self.server = None
|
|
||||||
self.publisher = self.ctx.socket(zmq.PUSH) # push update socket
|
|
||||||
self.publisher.setsockopt(zmq.IDENTITY, self.id)
|
|
||||||
self.publisher.setsockopt(zmq.SNDHWM, 60)
|
|
||||||
self.publisher.linger = 0
|
|
||||||
|
|
||||||
def control_message(self):
|
|
||||||
msg = self.pipe.recv_multipart()
|
|
||||||
command = msg.pop(0)
|
|
||||||
|
|
||||||
if command == b"CONNECT":
|
|
||||||
self.id = msg.pop(0)
|
|
||||||
address = msg.pop(0)
|
|
||||||
port = int(msg.pop(0))
|
|
||||||
|
|
||||||
if self.server is None:
|
|
||||||
if address == '127.0.0.1' or address == 'localhost':
|
|
||||||
self.admin = True
|
|
||||||
self.server = Server(self.ctx, address, port, self.id)
|
|
||||||
self.publisher.connect(
|
|
||||||
"tcp://{}:{}".format(address.decode(), port+2))
|
|
||||||
|
|
||||||
else:
|
|
||||||
logger.error("E: too many servers (max. %i)", SERVER_MAX)
|
|
||||||
|
|
||||||
elif command == b"DISCONNECT":
|
|
||||||
if self.admin is False:
|
|
||||||
uid = self.id.decode()
|
|
||||||
|
|
||||||
delete_user = message.Message(
|
|
||||||
key="Client/{}".format(uid), id=self.id, body=None)
|
|
||||||
delete_user.send(self.publisher)
|
|
||||||
|
|
||||||
# TODO: Do we need to pass every object rights to the moderator on disconnect?
|
|
||||||
# for k,v in self.property_map.items():
|
|
||||||
# if v.body["id"] == uid:
|
|
||||||
# delete_msg = message.Message(
|
|
||||||
# key=k, id=self.id, body=None)
|
|
||||||
# # delete_msg.store(self.property_map)
|
|
||||||
# delete_msg.send(self.publisher)
|
|
||||||
|
|
||||||
elif command == b"SET":
|
|
||||||
key = umsgpack.unpackb(msg[0])
|
|
||||||
value = umsgpack.unpackb(msg[1])
|
|
||||||
override = umsgpack.unpackb(msg[2])
|
|
||||||
|
|
||||||
if key in self.property_map.keys():
|
|
||||||
if self.property_map[key].body['id'] == self.id.decode() or override:
|
|
||||||
if value == 'None':
|
|
||||||
value = helpers.dump(key)
|
|
||||||
value['id'] = self.id.decode()
|
|
||||||
if value:
|
|
||||||
key_id = self.id
|
|
||||||
msg = message.Message(
|
|
||||||
key=key, id=key_id, body=value)
|
|
||||||
|
|
||||||
msg.store(self.property_map)
|
|
||||||
|
|
||||||
if override:
|
|
||||||
helpers.load(key, self.property_map[key].body)
|
|
||||||
msg.send(self.publisher)
|
|
||||||
else:
|
|
||||||
logger.error("Fail to dump ")
|
|
||||||
else:
|
|
||||||
helpers.load(key, self.property_map[key].body)
|
|
||||||
|
|
||||||
elif command == b"ADD":
|
|
||||||
key = umsgpack.unpackb(msg[0])
|
|
||||||
value = umsgpack.unpackb(msg[1])
|
|
||||||
|
|
||||||
if value == 'None':
|
|
||||||
value = helpers.dump(key)
|
|
||||||
value['id'] = self.id.decode()
|
|
||||||
if value:
|
|
||||||
msg = message.Message(
|
|
||||||
key=key, id=self.id, body=value)
|
|
||||||
|
|
||||||
msg.store(self.property_map)
|
|
||||||
msg.send(self.publisher)
|
|
||||||
else:
|
|
||||||
logger.error("Fail to dump ")
|
|
||||||
|
|
||||||
elif command == b"GET":
|
|
||||||
value = []
|
|
||||||
key = umsgpack.unpackb(msg[0])
|
|
||||||
for k in self.property_map.keys():
|
|
||||||
if key in k:
|
|
||||||
value.append([k, self.property_map.get(k).body])
|
|
||||||
|
|
||||||
self.pipe.send(umsgpack.packb(value)
|
|
||||||
if value else umsgpack.packb(''))
|
|
||||||
|
|
||||||
elif command == b"LIST":
|
|
||||||
dump_list = []
|
|
||||||
for k, v in self.property_map.items():
|
|
||||||
if 'Client' in k:
|
|
||||||
dump_list.append([k, v.id.decode()])
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
dump_list.append([k, v.body['id']])
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.pipe.send(umsgpack.packb(dump_list)
|
|
||||||
if dump_list else umsgpack.packb(''))
|
|
||||||
|
|
||||||
elif command == b"STATE":
|
|
||||||
self.pipe.send(umsgpack.packb(self.state.value))
|
|
||||||
|
|
||||||
|
|
||||||
def net_worker(ctx, store, pipe, serial_product, serial_feed, stop_event,external_executor):
|
|
||||||
agent = ClientAgent(ctx, store, pipe)
|
|
||||||
server = None
|
|
||||||
net_feed = serial_product
|
|
||||||
net_product = serial_feed
|
|
||||||
external_executor = external_executor
|
|
||||||
while not stop_event.is_set():
|
|
||||||
poller = zmq.Poller()
|
|
||||||
poller.register(agent.pipe, zmq.POLLIN)
|
|
||||||
server_socket = None
|
|
||||||
|
|
||||||
if agent.state == State.INITIAL:
|
|
||||||
server = agent.server
|
|
||||||
if agent.server:
|
|
||||||
logger.debug("%s: waiting for server at %s:%d...",
|
|
||||||
agent.id.decode(), server.address, server.port)
|
|
||||||
server.snapshot.send(b"SNAPSHOT_REQUEST")
|
|
||||||
agent.state = State.SYNCING
|
|
||||||
server_socket = server.snapshot
|
|
||||||
elif agent.state == State.SYNCING:
|
|
||||||
server_socket = server.snapshot
|
|
||||||
elif agent.state == State.ACTIVE:
|
|
||||||
server_socket = server.subscriber
|
|
||||||
|
|
||||||
if server_socket:
|
|
||||||
poller.register(server_socket, zmq.POLLIN)
|
|
||||||
|
|
||||||
try:
|
|
||||||
items = dict(poller.poll(1))
|
|
||||||
except:
|
|
||||||
raise
|
|
||||||
break
|
|
||||||
|
|
||||||
if agent.pipe in items:
|
|
||||||
agent.control_message()
|
|
||||||
elif server_socket in items:
|
|
||||||
msg = message.Message.recv(server_socket)
|
|
||||||
|
|
||||||
if agent.state == State.SYNCING:
|
|
||||||
# CLient snapshot
|
|
||||||
if msg.key == "SNAPSHOT_END":
|
|
||||||
client_key = "Client/{}".format(agent.id.decode())
|
|
||||||
|
|
||||||
client_dict = {}
|
|
||||||
client_dict = helpers.init_client(key=client_key)
|
|
||||||
client_dict['id'] = agent.id.decode()
|
|
||||||
|
|
||||||
client_store = message.Message(
|
|
||||||
key=client_key, id=agent.id, body=client_dict)
|
|
||||||
client_store.store(agent.property_map)
|
|
||||||
client_store.send(agent.publisher)
|
|
||||||
|
|
||||||
agent.state = State.ACTIVE
|
|
||||||
logger.debug("snapshot complete")
|
|
||||||
else:
|
|
||||||
net_product.put(('LOAD', msg.key, msg.body,False))
|
|
||||||
|
|
||||||
# helpers.load(msg.key, msg.body)
|
|
||||||
msg.store(agent.property_map)
|
|
||||||
logger.debug("snapshot from {} stored".format(msg.id))
|
|
||||||
elif agent.state == State.ACTIVE:
|
|
||||||
if msg.id != agent.id:
|
|
||||||
logger.debug("PULL: {} from {}".format(msg.key,msg.id))
|
|
||||||
|
|
||||||
msg.store(agent.property_map)
|
|
||||||
|
|
||||||
params = []
|
|
||||||
params.append(msg.key)
|
|
||||||
params.append(msg.body)
|
|
||||||
external_executor.put((helpers.load,params))
|
|
||||||
# net_product.put(('LOAD', msg.key, msg.body))
|
|
||||||
|
|
||||||
# Serialisation thread => Net thread
|
|
||||||
if not net_feed.empty():
|
|
||||||
key, value, id = net_feed.get()
|
|
||||||
if value:
|
|
||||||
logger.debug("SERIAL => NET: {} ".format(key))
|
|
||||||
|
|
||||||
if id is None:
|
|
||||||
# Stamp with id
|
|
||||||
value['id'] = agent.id.decode()
|
|
||||||
|
|
||||||
|
|
||||||
# Format massage
|
|
||||||
msg = message.Message(
|
|
||||||
key=key, id=agent.id, body=value)
|
|
||||||
|
|
||||||
msg.store(agent.property_map)
|
|
||||||
msg.send(agent.publisher)
|
|
||||||
else:
|
|
||||||
logger.error("Fail to dump ")
|
|
||||||
|
|
||||||
logger.info("exit thread")
|
|
||||||
|
|
||||||
|
|
||||||
def serial_worker(serial_product, serial_feed):
|
|
||||||
logger.info("serial thread launched")
|
|
||||||
|
|
||||||
while True:
|
|
||||||
command, key, value, id = serial_feed.get()
|
|
||||||
|
|
||||||
if command == 'STOP':
|
|
||||||
break
|
|
||||||
elif command == 'DUMP':
|
|
||||||
try:
|
|
||||||
value = helpers.dump(key)
|
|
||||||
|
|
||||||
if value:
|
|
||||||
serial_product.put((key, value, id))
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("{}".format(e))
|
|
||||||
elif command == 'LOAD':
|
|
||||||
if value:
|
|
||||||
try:
|
|
||||||
helpers.load(key, value)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("{}".format(e))
|
|
||||||
|
|
||||||
logger.info("serial thread stopped")
|
|
||||||
|
|
||||||
|
|
||||||
def watchdog_worker(serial_feed, interval, stop_event):
|
|
||||||
import bpy
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"watchdog thread launched with {} sec of interval".format(interval))
|
|
||||||
while not stop_event.is_set():
|
|
||||||
for datatype in environment.rtypes:
|
|
||||||
for item in getattr(bpy.data, helpers.BPY_TYPES[datatype]):
|
|
||||||
key = "{}/{}".format(datatype, item.name)
|
|
||||||
try:
|
|
||||||
if item.is_dirty:
|
|
||||||
logger.debug("{} needs update".format(key))
|
|
||||||
serial_feed.put(('DUMP', key, None, False))
|
|
||||||
item.is_dirty = False
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
time.sleep(interval)
|
|
||||||
|
|
||||||
logger.info("watchdog thread stopped")
|
|
||||||
|
|
||||||
|
|
92
delayable.py
Normal file
92
delayable.py
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
import bpy
|
||||||
|
from .libs.replication.constants import *
|
||||||
|
from .libs import debug
|
||||||
|
from . import operators, utils
|
||||||
|
from .bl_types.bl_user import BlUser
|
||||||
|
|
||||||
|
class Delayable():
|
||||||
|
"""Delayable task interface
|
||||||
|
"""
|
||||||
|
def register(self):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def unregister(self):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
class Timer(Delayable):
|
||||||
|
"""Timer binder interface for blender
|
||||||
|
|
||||||
|
Run a bpy.app.Timer in the background looping at the given rate
|
||||||
|
"""
|
||||||
|
def __init__(self, duration=1):
|
||||||
|
self._timeout = duration
|
||||||
|
|
||||||
|
def register(self):
|
||||||
|
"""Register the timer into the blender timer system
|
||||||
|
"""
|
||||||
|
bpy.app.timers.register(self.execute)
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
"""Main timer loop
|
||||||
|
"""
|
||||||
|
return self._timeout
|
||||||
|
|
||||||
|
def unregister(self):
|
||||||
|
"""Unnegister the timer of the blender timer system
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
bpy.app.timers.unregister(self.execute)
|
||||||
|
except:
|
||||||
|
print("timer already unregistered")
|
||||||
|
|
||||||
|
class ApplyTimer(Timer):
|
||||||
|
def __init__(self, timout=1,target_type=None):
|
||||||
|
self._type = target_type
|
||||||
|
super().__init__(timout)
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
if operators.client:
|
||||||
|
nodes = operators.client.list(filter=self._type)
|
||||||
|
|
||||||
|
for node in nodes:
|
||||||
|
node_ref = operators.client.get(node)
|
||||||
|
|
||||||
|
if node_ref.state == FETCHED:
|
||||||
|
operators.client.apply(uuid=node)
|
||||||
|
|
||||||
|
return self._timeout
|
||||||
|
|
||||||
|
class Draw(Delayable):
|
||||||
|
def __init__(self):
|
||||||
|
self._handler = None
|
||||||
|
|
||||||
|
def register(self):
|
||||||
|
self._handler = bpy.types.SpaceView3D.draw_handler_add(
|
||||||
|
self.execute,(), 'WINDOW', 'POST_VIEW')
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def unregister(self):
|
||||||
|
try:
|
||||||
|
bpy.types.SpaceView3D.draw_handler_remove(
|
||||||
|
self._handler, "WINDOW")
|
||||||
|
except:
|
||||||
|
print("draw already unregistered")
|
||||||
|
|
||||||
|
class ClientUpdate(Draw):
|
||||||
|
def __init__(self, client_uuid=None):
|
||||||
|
assert(client_uuid)
|
||||||
|
self._client_uuid = client_uuid
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
if hasattr(operators,"client"):
|
||||||
|
client = operators.client.get(self._client_uuid)
|
||||||
|
|
||||||
|
if client:
|
||||||
|
client.pointer.update_location()
|
||||||
|
|
@ -133,6 +133,7 @@ def setup(dependencies, python_path):
|
|||||||
PYTHON_PATH = Path(python_path)
|
PYTHON_PATH = Path(python_path)
|
||||||
SUBPROCESS_DIR = PYTHON_PATH.parent
|
SUBPROCESS_DIR = PYTHON_PATH.parent
|
||||||
|
|
||||||
|
|
||||||
if not module_can_be_imported("pip"):
|
if not module_can_be_imported("pip"):
|
||||||
install_pip()
|
install_pip()
|
||||||
|
|
||||||
|
830
helpers.py
830
helpers.py
@ -1,830 +0,0 @@
|
|||||||
import logging
|
|
||||||
import sys
|
|
||||||
from uuid import uuid4
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
|
|
||||||
import bpy
|
|
||||||
import mathutils
|
|
||||||
|
|
||||||
from . import draw, environment
|
|
||||||
from .libs import dump_anything
|
|
||||||
|
|
||||||
# TODO: replace hardcoded values...
|
|
||||||
BPY_TYPES = {'Image': 'images', 'Texture': 'textures', 'Material': 'materials', 'GreasePencil': 'grease_pencils', 'Curve': 'curves', 'Collection': 'collections', 'Mesh': 'meshes', 'Object': 'objects',
|
|
||||||
'Scene': 'scenes', 'Light': 'lights', 'SunLight': 'lights', 'SpotLight': 'lights', 'AreaLight': 'lights', 'PointLight': 'lights', 'Camera': 'cameras', 'Action': 'actions', 'Armature': 'armatures'}
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
logger.setLevel(logging.DEBUG)
|
|
||||||
|
|
||||||
# UTILITY FUNCTIONS
|
|
||||||
|
|
||||||
|
|
||||||
def revers(d):
|
|
||||||
l = []
|
|
||||||
for i in d:
|
|
||||||
l.append(i)
|
|
||||||
|
|
||||||
return l[::-1]
|
|
||||||
|
|
||||||
|
|
||||||
def refresh_window():
|
|
||||||
import bpy
|
|
||||||
|
|
||||||
bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
|
|
||||||
|
|
||||||
|
|
||||||
def get_armature_edition_context(armature):
|
|
||||||
|
|
||||||
override = {}
|
|
||||||
# Set correct area
|
|
||||||
for area in bpy.data.window_managers[0].windows[0].screen.areas:
|
|
||||||
if area.type == 'VIEW_3D':
|
|
||||||
override = bpy.context.copy()
|
|
||||||
override['area'] = area
|
|
||||||
break
|
|
||||||
|
|
||||||
# Set correct armature settings
|
|
||||||
override['window'] = bpy.data.window_managers[0].windows[0]
|
|
||||||
override['screen'] = bpy.data.window_managers[0].windows[0].screen
|
|
||||||
override['mode'] = 'EDIT_ARMATURE'
|
|
||||||
override['active_object'] = armature
|
|
||||||
override['selected_objects'] = [armature]
|
|
||||||
|
|
||||||
for o in bpy.data.objects:
|
|
||||||
if o.data == armature:
|
|
||||||
override['edit_object'] = o
|
|
||||||
|
|
||||||
break
|
|
||||||
|
|
||||||
return override
|
|
||||||
|
|
||||||
|
|
||||||
def get_selected_objects(scene):
|
|
||||||
selected_objects = []
|
|
||||||
for obj in scene.objects:
|
|
||||||
if obj.select_get():
|
|
||||||
selected_objects.append(obj.name)
|
|
||||||
|
|
||||||
return selected_objects
|
|
||||||
|
|
||||||
|
|
||||||
# LOAD HELPERS
|
|
||||||
|
|
||||||
def load_dict(src_dict, target):
|
|
||||||
try:
|
|
||||||
for item in src_dict:
|
|
||||||
# attr =
|
|
||||||
setattr(target, item, src_dict[item])
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(e)
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def load(key, value):
|
|
||||||
target = resolve_bpy_path(key)
|
|
||||||
target_type = key.split('/')[0]
|
|
||||||
|
|
||||||
logger.debug("load{}, {}".format(target_type, key))
|
|
||||||
if value == "None":
|
|
||||||
return
|
|
||||||
|
|
||||||
if target_type == 'Object':
|
|
||||||
load_object(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'Image':
|
|
||||||
load_image(target=target, data=value)
|
|
||||||
elif target_type == 'Mesh':
|
|
||||||
load_mesh(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'Collection':
|
|
||||||
load_collection(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'Material':
|
|
||||||
load_material(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'GreasePencil':
|
|
||||||
load_gpencil(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'Scene':
|
|
||||||
load_scene(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif 'Light' in target_type:
|
|
||||||
load_light(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'Camera':
|
|
||||||
load_default(target=target, data=value,
|
|
||||||
create=True, type=target_type)
|
|
||||||
elif target_type == 'Armature':
|
|
||||||
load_armature(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'Curve':
|
|
||||||
load_curve(target=target, data=value,
|
|
||||||
create=True)
|
|
||||||
elif target_type == 'Client':
|
|
||||||
load_client(key.split('/')[1], value)
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_bpy_path(path):
|
|
||||||
"""
|
|
||||||
Get bpy property value from path
|
|
||||||
"""
|
|
||||||
item = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
path = path.split('/')
|
|
||||||
item = getattr(bpy.data, BPY_TYPES[path[0]])[path[1]]
|
|
||||||
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return item
|
|
||||||
|
|
||||||
|
|
||||||
def load_client(client=None, data=None):
|
|
||||||
C = bpy.context
|
|
||||||
D = bpy.data
|
|
||||||
net_settings = C.window_manager.session
|
|
||||||
|
|
||||||
if client and data:
|
|
||||||
if net_settings.enable_presence:
|
|
||||||
draw.renderer.draw_client(data)
|
|
||||||
draw.renderer.draw_client_selected_objects(data)
|
|
||||||
|
|
||||||
|
|
||||||
def load_image(target=None, data=None):
|
|
||||||
try:
|
|
||||||
if not target:
|
|
||||||
image = bpy.data.images.new(
|
|
||||||
name=data['name'],
|
|
||||||
width=data['size'][0],
|
|
||||||
height=data['size'][1]
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
image = target
|
|
||||||
|
|
||||||
img_name = "{}.png".format(image.name)
|
|
||||||
|
|
||||||
logger.info("updating {} cache file".format(image.name))
|
|
||||||
img_path = os.path.join(environment.CACHE_DIR, img_name)
|
|
||||||
|
|
||||||
file = open(img_path, 'wb')
|
|
||||||
file.write(data["pixels"])
|
|
||||||
file.close()
|
|
||||||
|
|
||||||
image.source = 'FILE'
|
|
||||||
image.filepath = img_path
|
|
||||||
# dump_anything.load(target, data)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(e)
|
|
||||||
|
|
||||||
|
|
||||||
def load_armature(target=None, data=None, create=False):
|
|
||||||
file = "cache_{}.json".format(data['name'])
|
|
||||||
context = bpy.context
|
|
||||||
|
|
||||||
if not target:
|
|
||||||
target = bpy.data.armatures.new(data['name'])
|
|
||||||
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
with open(file, 'w') as fp:
|
|
||||||
json.dump(data, fp)
|
|
||||||
fp.close()
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
else:
|
|
||||||
# Construct a correct execution context
|
|
||||||
file = "cache_{}.json".format(target.name)
|
|
||||||
|
|
||||||
with open(file, 'r') as fp:
|
|
||||||
data = json.load(fp)
|
|
||||||
|
|
||||||
if data:
|
|
||||||
ob = None
|
|
||||||
for o in bpy.data.objects:
|
|
||||||
if o.data == target:
|
|
||||||
ob = o
|
|
||||||
if ob:
|
|
||||||
bpy.context.view_layer.objects.active = ob
|
|
||||||
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
|
|
||||||
for eb in data['edit_bones']:
|
|
||||||
if eb in target.edit_bones.keys():
|
|
||||||
# Update the bone
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
# Add new edit bone and load it
|
|
||||||
|
|
||||||
target_new_b = target.edit_bones.new[eb]
|
|
||||||
dump_anything.load(target_new_b, data['bones'][eb])
|
|
||||||
|
|
||||||
logger.debug(eb)
|
|
||||||
|
|
||||||
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
|
|
||||||
fp.close()
|
|
||||||
import os
|
|
||||||
os.remove(file)
|
|
||||||
|
|
||||||
|
|
||||||
def load_mesh(target=None, data=None, create=False):
|
|
||||||
import bmesh
|
|
||||||
|
|
||||||
if not target or not target.is_editmode:
|
|
||||||
# 1 - LOAD GEOMETRY
|
|
||||||
mesh_buffer = bmesh.new()
|
|
||||||
|
|
||||||
for i in data["verts"]:
|
|
||||||
v = mesh_buffer.verts.new(data["verts"][i]["co"])
|
|
||||||
|
|
||||||
mesh_buffer.verts.ensure_lookup_table()
|
|
||||||
|
|
||||||
for i in data["edges"]:
|
|
||||||
verts = mesh_buffer.verts
|
|
||||||
v1 = data["edges"][i]["verts"][0]
|
|
||||||
v2 = data["edges"][i]["verts"][1]
|
|
||||||
mesh_buffer.edges.new([verts[v1], verts[v2]])
|
|
||||||
|
|
||||||
for p in data["faces"]:
|
|
||||||
verts = []
|
|
||||||
for v in data["faces"][p]["verts"]:
|
|
||||||
verts.append(mesh_buffer.verts[v])
|
|
||||||
|
|
||||||
if len(verts) > 0:
|
|
||||||
f = mesh_buffer.faces.new(verts)
|
|
||||||
|
|
||||||
uv_layer = mesh_buffer.loops.layers.uv.verify()
|
|
||||||
|
|
||||||
f.material_index = data["faces"][p]['material_index']
|
|
||||||
|
|
||||||
# UV loading
|
|
||||||
for i, loop in enumerate(f.loops):
|
|
||||||
loop_uv = loop[uv_layer]
|
|
||||||
loop_uv.uv = data["faces"][p]["uv"][i]
|
|
||||||
|
|
||||||
if target is None and create:
|
|
||||||
target = bpy.data.meshes.new(data["name"])
|
|
||||||
|
|
||||||
mesh_buffer.to_mesh(target)
|
|
||||||
|
|
||||||
# mesh_buffer.from_mesh(target)
|
|
||||||
|
|
||||||
# 2 - LOAD METADATA
|
|
||||||
|
|
||||||
# uv's
|
|
||||||
for uv_layer in data['uv_layers']:
|
|
||||||
target.uv_layers.new(name=uv_layer)
|
|
||||||
|
|
||||||
bevel_layer = mesh_buffer.verts.layers.bevel_weight.verify()
|
|
||||||
skin_layer = mesh_buffer.verts.layers.skin.verify()
|
|
||||||
|
|
||||||
# for face in mesh_buffer.faces:
|
|
||||||
|
|
||||||
# # Face metadata
|
|
||||||
# for loop in face.loops:
|
|
||||||
# loop_uv = loop[uv_layer]
|
|
||||||
# loop_uv.uv = data['faces'][face.index]["uv"]
|
|
||||||
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
# 3 - LOAD MATERIAL SLOTS
|
|
||||||
material_to_load = []
|
|
||||||
material_to_load = revers(data["materials"])
|
|
||||||
target.materials.clear()
|
|
||||||
# SLots
|
|
||||||
i = 0
|
|
||||||
|
|
||||||
for m in data["material_list"]:
|
|
||||||
target.materials.append(bpy.data.materials[m])
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
else:
|
|
||||||
logger.error("Mesh can't be loaded")
|
|
||||||
|
|
||||||
|
|
||||||
def load_object(target=None, data=None, create=False):
|
|
||||||
try:
|
|
||||||
if target is None and create:
|
|
||||||
pointer = None
|
|
||||||
|
|
||||||
# Object specific constructor...
|
|
||||||
if data["data"] in bpy.data.meshes.keys():
|
|
||||||
pointer = bpy.data.meshes[data["data"]]
|
|
||||||
elif data["data"] in bpy.data.lights.keys():
|
|
||||||
pointer = bpy.data.lights[data["data"]]
|
|
||||||
elif data["data"] in bpy.data.cameras.keys():
|
|
||||||
pointer = bpy.data.cameras[data["data"]]
|
|
||||||
elif data["data"] in bpy.data.curves.keys():
|
|
||||||
pointer = bpy.data.curves[data["data"]]
|
|
||||||
elif data["data"] in bpy.data.armatures.keys():
|
|
||||||
pointer = bpy.data.armatures[data["data"]]
|
|
||||||
elif data["data"] in bpy.data.grease_pencils.keys():
|
|
||||||
pointer = bpy.data.grease_pencils[data["data"]]
|
|
||||||
elif data["data"] in bpy.data.curves.keys():
|
|
||||||
pointer = bpy.data.curves[data["data"]]
|
|
||||||
|
|
||||||
target = bpy.data.objects.new(data["name"], pointer)
|
|
||||||
|
|
||||||
# Load other meshes metadata
|
|
||||||
# dump_anything.load(target, data)
|
|
||||||
|
|
||||||
target.matrix_world = mathutils.Matrix(data["matrix_world"])
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
|
|
||||||
client = bpy.context.window_manager.session.username
|
|
||||||
|
|
||||||
# Load modifiers
|
|
||||||
if hasattr(target,'modifiers'):
|
|
||||||
for local_modifier in target.modifiers:
|
|
||||||
if local_modifier.name not in data['modifiers']:
|
|
||||||
target.modifiers.remove(local_modifier)
|
|
||||||
for modifier in data['modifiers']:
|
|
||||||
target_modifier = target.modifiers.get(modifier)
|
|
||||||
|
|
||||||
if not target_modifier:
|
|
||||||
target_modifier = target.modifiers.new(data['modifiers'][modifier]['name'],data['modifiers'][modifier]['type'])
|
|
||||||
|
|
||||||
dump_anything.load(target_modifier, data['modifiers'][modifier])
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if target.id == client or target.id == "Common":
|
|
||||||
target.hide_select = False
|
|
||||||
else:
|
|
||||||
target.hide_select = True
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Object {} loading error: {} ".format(data["name"], e))
|
|
||||||
|
|
||||||
|
|
||||||
def load_curve(target=None, data=None, create=False):
|
|
||||||
try:
|
|
||||||
if target is None and create:
|
|
||||||
target = bpy.data.curves.new(data["name"], 'CURVE')
|
|
||||||
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
target.splines.clear()
|
|
||||||
# load splines
|
|
||||||
for spline in data['splines']:
|
|
||||||
# Update existing..
|
|
||||||
# if spline in target.splines.keys():
|
|
||||||
|
|
||||||
new_spline = target.splines.new(data['splines'][spline]['type'])
|
|
||||||
dump_anything.load(new_spline, data['splines'][spline])
|
|
||||||
|
|
||||||
# Load curve geometry data
|
|
||||||
for bezier_point_index in data['splines'][spline]["bezier_points"]:
|
|
||||||
new_spline.bezier_points.add(1)
|
|
||||||
dump_anything.load(
|
|
||||||
new_spline.bezier_points[bezier_point_index], data['splines'][spline]["bezier_points"][bezier_point_index])
|
|
||||||
|
|
||||||
for point_index in data['splines'][spline]["points"]:
|
|
||||||
new_spline.points.add(1)
|
|
||||||
dump_anything.load(
|
|
||||||
new_spline.points[point_index], data['splines'][spline]["points"][point_index])
|
|
||||||
target.id = data['id']
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("curve loading error: {}".format(e))
|
|
||||||
|
|
||||||
|
|
||||||
def load_collection(target=None, data=None, create=False):
|
|
||||||
try:
|
|
||||||
if target is None and create:
|
|
||||||
target = bpy.data.collections.new(data["name"])
|
|
||||||
|
|
||||||
# Load other meshes metadata
|
|
||||||
# dump_anything.load(target, data)
|
|
||||||
|
|
||||||
# link objects
|
|
||||||
for object in data["objects"]:
|
|
||||||
if object not in target.objects.keys():
|
|
||||||
target.objects.link(bpy.data.objects[object])
|
|
||||||
|
|
||||||
for object in target.objects.keys():
|
|
||||||
if object not in data["objects"]:
|
|
||||||
target.objects.unlink(bpy.data.objects[object])
|
|
||||||
|
|
||||||
# Link childrens
|
|
||||||
for collection in data["children"]:
|
|
||||||
if collection not in target.children.keys():
|
|
||||||
if bpy.data.collections.find(collection) == -1:
|
|
||||||
target.children.link(
|
|
||||||
bpy.data.collections[collection])
|
|
||||||
else:
|
|
||||||
logger.debug(target.name)
|
|
||||||
|
|
||||||
for collection in target.children.keys():
|
|
||||||
if collection not in data["children"]:
|
|
||||||
target.collection.children.unlink(
|
|
||||||
bpy.data.collections[collection])
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
|
|
||||||
client = bpy.context.window_manager.session.username
|
|
||||||
|
|
||||||
if target.id == client or target.id == "Common":
|
|
||||||
target.hide_select = False
|
|
||||||
else:
|
|
||||||
target.hide_select = True
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Collection loading error: {}".format(e))
|
|
||||||
|
|
||||||
|
|
||||||
def load_scene(target=None, data=None, create=False):
|
|
||||||
try:
|
|
||||||
if target is None and create:
|
|
||||||
target = bpy.data.scenes.new(data["name"])
|
|
||||||
|
|
||||||
# Load other meshes metadata
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
# Load master collection
|
|
||||||
for object in data["collection"]["objects"]:
|
|
||||||
if object not in target.collection.objects.keys():
|
|
||||||
target.collection.objects.link(bpy.data.objects[object])
|
|
||||||
|
|
||||||
for object in target.collection.objects.keys():
|
|
||||||
if object not in data["collection"]["objects"]:
|
|
||||||
target.collection.objects.unlink(bpy.data.objects[object])
|
|
||||||
|
|
||||||
# load collections
|
|
||||||
# TODO: Recursive link
|
|
||||||
logger.debug("check for scene childs")
|
|
||||||
for collection in data["collection"]["children"]:
|
|
||||||
logger.debug(collection)
|
|
||||||
if collection not in target.collection.children.keys():
|
|
||||||
target.collection.children.link(
|
|
||||||
bpy.data.collections[collection])
|
|
||||||
|
|
||||||
logger.debug("check for scene child to remove")
|
|
||||||
for collection in target.collection.children.keys():
|
|
||||||
if collection not in data["collection"]["children"]:
|
|
||||||
target.collection.children.unlink(
|
|
||||||
bpy.data.collections[collection])
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
# Load annotation
|
|
||||||
# if data["grease_pencil"]:
|
|
||||||
# target.grease_pencil = bpy.data.grease_pencils[data["grease_pencil"]["name"]]
|
|
||||||
# else:
|
|
||||||
# target.grease_pencil = None
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Scene loading error: {}".format(e))
|
|
||||||
|
|
||||||
|
|
||||||
def load_material(target=None, data=None, create=False):
|
|
||||||
try:
|
|
||||||
if target is None:
|
|
||||||
target = bpy.data.materials.new(data["name"])
|
|
||||||
|
|
||||||
if data['is_grease_pencil']:
|
|
||||||
if not target.is_grease_pencil:
|
|
||||||
bpy.data.materials.create_gpencil_data(target)
|
|
||||||
|
|
||||||
dump_anything.load(target.grease_pencil, data['grease_pencil'])
|
|
||||||
|
|
||||||
load_dict(data['grease_pencil'], target.grease_pencil)
|
|
||||||
|
|
||||||
elif data["use_nodes"]:
|
|
||||||
if target.node_tree is None:
|
|
||||||
target.use_nodes = True
|
|
||||||
|
|
||||||
target.node_tree.nodes.clear()
|
|
||||||
|
|
||||||
for node in data["node_tree"]["nodes"]:
|
|
||||||
# fix None node tree error
|
|
||||||
|
|
||||||
index = target.node_tree.nodes.find(node)
|
|
||||||
|
|
||||||
if index is -1:
|
|
||||||
node_type = data["node_tree"]["nodes"][node]["bl_idname"]
|
|
||||||
|
|
||||||
target.node_tree.nodes.new(type=node_type)
|
|
||||||
|
|
||||||
dump_anything.load(
|
|
||||||
target.node_tree.nodes[index], data["node_tree"]["nodes"][node])
|
|
||||||
|
|
||||||
if data["node_tree"]["nodes"][node]['type'] == 'TEX_IMAGE':
|
|
||||||
target.node_tree.nodes[index].image = bpy.data.images[data["node_tree"]
|
|
||||||
["nodes"][node]['image']['name']]
|
|
||||||
|
|
||||||
for input in data["node_tree"]["nodes"][node]["inputs"]:
|
|
||||||
|
|
||||||
try:
|
|
||||||
if hasattr(target.node_tree.nodes[index].inputs[input], "default_value"):
|
|
||||||
target.node_tree.nodes[index].inputs[input].default_value = data[
|
|
||||||
"node_tree"]["nodes"][node]["inputs"][input]["default_value"]
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Fail loading {} node value from {} ({}) ".format(
|
|
||||||
target.name, target.node_tree.nodes[index].inputs[input].default_value, e))
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Load nodes links
|
|
||||||
target.node_tree.links.clear()
|
|
||||||
|
|
||||||
for link in data["node_tree"]["links"]:
|
|
||||||
current_link = data["node_tree"]["links"][link]
|
|
||||||
input_socket = target.node_tree.nodes[current_link['to_node']
|
|
||||||
['name']].inputs[current_link['to_socket']['name']]
|
|
||||||
output_socket = target.node_tree.nodes[current_link['from_node']
|
|
||||||
['name']].outputs[current_link['from_socket']['name']]
|
|
||||||
|
|
||||||
target.node_tree.links.new(input_socket, output_socket)
|
|
||||||
|
|
||||||
# Load other meshes metadata
|
|
||||||
# dump_anything.load(target, data)
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Material loading error: {}".format(e))
|
|
||||||
|
|
||||||
|
|
||||||
def load_gpencil_layer(target=None, data=None, create=False):
|
|
||||||
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
for frame in data["frames"]:
|
|
||||||
try:
|
|
||||||
tframe = target.frames[frame]
|
|
||||||
except:
|
|
||||||
tframe = target.frames.new(frame)
|
|
||||||
dump_anything.load(tframe, data["frames"][frame])
|
|
||||||
for stroke in data["frames"][frame]["strokes"]:
|
|
||||||
try:
|
|
||||||
tstroke = tframe.strokes[stroke]
|
|
||||||
except:
|
|
||||||
tstroke = tframe.strokes.new()
|
|
||||||
dump_anything.load(
|
|
||||||
tstroke, data["frames"][frame]["strokes"][stroke])
|
|
||||||
|
|
||||||
for point in data["frames"][frame]["strokes"][stroke]["points"]:
|
|
||||||
p = data["frames"][frame]["strokes"][stroke]["points"][point]
|
|
||||||
|
|
||||||
tstroke.points.add(1)
|
|
||||||
tpoint = tstroke.points[len(tstroke.points)-1]
|
|
||||||
|
|
||||||
dump_anything.load(tpoint, p)
|
|
||||||
|
|
||||||
|
|
||||||
def load_gpencil(target=None, data=None, create=False):
|
|
||||||
try:
|
|
||||||
if target is None and create:
|
|
||||||
target = bpy.data.grease_pencils.new(data["name"])
|
|
||||||
|
|
||||||
for layer in target.layers:
|
|
||||||
target.layers.remove(layer)
|
|
||||||
|
|
||||||
if "layers" in data.keys():
|
|
||||||
for layer in data["layers"]:
|
|
||||||
if layer not in target.layers.keys():
|
|
||||||
gp_layer = target.layers.new(data["layers"][layer]["info"])
|
|
||||||
else:
|
|
||||||
gp_layer = target.layers[layer]
|
|
||||||
load_gpencil_layer(
|
|
||||||
target=gp_layer, data=data["layers"][layer], create=create)
|
|
||||||
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
target.materials.clear()
|
|
||||||
if "materials" in data.keys():
|
|
||||||
for mat in data['materials']:
|
|
||||||
target.materials.append(bpy.data.materials[mat])
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
except:
|
|
||||||
logger.error("default loadi\ng error")
|
|
||||||
|
|
||||||
|
|
||||||
def load_light(target=None, data=None, create=False, type=None):
|
|
||||||
try:
|
|
||||||
if target is None and create:
|
|
||||||
target = bpy.data.lights.new(data["name"], data["type"])
|
|
||||||
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("light loading error: {}".format(e))
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def load_default(target=None, data=None, create=False, type=None):
|
|
||||||
try:
|
|
||||||
if target is None and create:
|
|
||||||
target = getattr(bpy.data, BPY_TYPES[type]).new(data["name"])
|
|
||||||
|
|
||||||
dump_anything.load(target, data)
|
|
||||||
|
|
||||||
target.id = data['id']
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("default loading error {}".format(e))
|
|
||||||
|
|
||||||
# DUMP HELPERS
|
|
||||||
def dump(key):
|
|
||||||
target = resolve_bpy_path(key)
|
|
||||||
target_type = key.split('/')[0]
|
|
||||||
data = None
|
|
||||||
|
|
||||||
if target_type == 'Image':
|
|
||||||
data = {}
|
|
||||||
data['pixels'] = dump_image(target)
|
|
||||||
dump_datablock_attibutes(target, [], 2, data)
|
|
||||||
data = dump_datablock_attibutes(
|
|
||||||
target,
|
|
||||||
["name", 'size', 'height', 'alpha', 'float_buffer', 'filepath', 'source'],
|
|
||||||
2,
|
|
||||||
data)
|
|
||||||
elif target_type == 'Material':
|
|
||||||
data = dump_datablock(target, 2)
|
|
||||||
if target.node_tree:
|
|
||||||
dump_datablock_attibutes(
|
|
||||||
target.node_tree, ["nodes", "links"], 5, data['node_tree'])
|
|
||||||
elif target.grease_pencil:
|
|
||||||
dump_datablock_attibutes(target, ["grease_pencil"], 3, data)
|
|
||||||
elif target_type == 'GreasePencil':
|
|
||||||
data = dump_datablock(target, 2)
|
|
||||||
dump_datablock_attibutes(
|
|
||||||
target, ['layers'], 9, data)
|
|
||||||
elif target_type == 'Camera':
|
|
||||||
data = dump_datablock(target, 1)
|
|
||||||
elif 'Light' in target_type:
|
|
||||||
data = dump_datablock(target, 3)
|
|
||||||
elif target_type == 'Mesh':
|
|
||||||
data = dump_datablock(target, 2)
|
|
||||||
data = dump_mesh(target, data)
|
|
||||||
# dump_datablock_attibutes(
|
|
||||||
# target, ['name', 'polygons', 'edges', 'vertices', 'id'], 6, data)
|
|
||||||
|
|
||||||
# Fix material index
|
|
||||||
m_list = []
|
|
||||||
for m in target.materials:
|
|
||||||
m_list.append(m.name)
|
|
||||||
|
|
||||||
data['material_list'] = m_list
|
|
||||||
elif target_type == 'Curve':
|
|
||||||
data = dump_datablock(target, 1)
|
|
||||||
dump_datablock_attibutes(
|
|
||||||
target, ['splines'], 5, data)
|
|
||||||
# for index, spline in enumerate(target.splines):
|
|
||||||
# data["splines"][index] = dump_datablock_attibutes(target.splines[index],"Curve/{}".format(index), ["bezier_points", "material_index", "points", "order_u", "order_v", "point_count_u", "point_count_v",
|
|
||||||
# "radius_interpolation", "resolution_v", "use_bezier_u", "use_bezier_v", "use_cyclic_u", "use_cyclic_v", "use_endpoint_u", "use_endpoint_v"], 3)
|
|
||||||
elif target_type == 'Object':
|
|
||||||
data = dump_datablock(target, 1)
|
|
||||||
|
|
||||||
if hasattr(target,'modifiers'):
|
|
||||||
dump_datablock_attibutes(
|
|
||||||
target, ['modifiers'], 3, data)
|
|
||||||
elif target_type == 'Collection':
|
|
||||||
data = dump_datablock(target, 4)
|
|
||||||
elif target_type == 'Scene':
|
|
||||||
data = dump_datablock_attibutes(
|
|
||||||
target, ['name', 'collection', 'id', 'camera', 'grease_pencil'], 2)
|
|
||||||
dump_datablock_attibutes(
|
|
||||||
target, ['collection'], 4, data)
|
|
||||||
|
|
||||||
# elif target_type == 'Armature':
|
|
||||||
# data = dump_datablock(target, 4)
|
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def dump_datablock(datablock, depth):
|
|
||||||
if datablock:
|
|
||||||
dumper = dump_anything.Dumper()
|
|
||||||
dumper.type_subset = dumper.match_subset_all
|
|
||||||
dumper.depth = depth
|
|
||||||
|
|
||||||
datablock_type = datablock.bl_rna.name
|
|
||||||
key = "{}/{}".format(datablock_type, datablock.name)
|
|
||||||
data = dumper.dump(datablock)
|
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def dump_datablock_attibutes(datablock=None, attributes=[], depth=1, dickt=None):
|
|
||||||
if datablock:
|
|
||||||
dumper = dump_anything.Dumper()
|
|
||||||
dumper.type_subset = dumper.match_subset_all
|
|
||||||
dumper.depth = depth
|
|
||||||
|
|
||||||
datablock_type = datablock.bl_rna.name
|
|
||||||
key = "{}/{}".format(datablock_type, datablock.name)
|
|
||||||
|
|
||||||
data = {}
|
|
||||||
|
|
||||||
if dickt:
|
|
||||||
data = dickt
|
|
||||||
for attr in attributes:
|
|
||||||
try:
|
|
||||||
data[attr] = dumper.dump(getattr(datablock, attr))
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def dump_image(image):
|
|
||||||
pixels = None
|
|
||||||
if image.source == "GENERATED":
|
|
||||||
img_name = "{}.png".format(image.name)
|
|
||||||
|
|
||||||
image.filepath_raw = os.path.join(environment.CACHE_DIR, img_name)
|
|
||||||
image.file_format = "PNG"
|
|
||||||
image.save()
|
|
||||||
|
|
||||||
if image.source == "FILE":
|
|
||||||
image.save()
|
|
||||||
file = open(image.filepath_raw, "rb")
|
|
||||||
pixels = file.read()
|
|
||||||
logger.debug("Reading image file {}".format(image.name))
|
|
||||||
else:
|
|
||||||
logger.error("image format not supported")
|
|
||||||
return pixels
|
|
||||||
|
|
||||||
|
|
||||||
def dump_mesh(mesh, data={}):
|
|
||||||
import bmesh
|
|
||||||
|
|
||||||
mesh_data = data
|
|
||||||
mesh_buffer = bmesh.new()
|
|
||||||
|
|
||||||
mesh_buffer.from_mesh(mesh)
|
|
||||||
|
|
||||||
uv_layer = mesh_buffer.loops.layers.uv.verify()
|
|
||||||
bevel_layer = mesh_buffer.verts.layers.bevel_weight.verify()
|
|
||||||
skin_layer = mesh_buffer.verts.layers.skin.verify()
|
|
||||||
|
|
||||||
verts = {}
|
|
||||||
for vert in mesh_buffer.verts:
|
|
||||||
v = {}
|
|
||||||
v["co"] = list(vert.co)
|
|
||||||
|
|
||||||
# vert metadata
|
|
||||||
v['bevel'] = vert[bevel_layer]
|
|
||||||
# v['skin'] = list(vert[skin_layer])
|
|
||||||
|
|
||||||
verts[str(vert.index)] = v
|
|
||||||
|
|
||||||
mesh_data["verts"] = verts
|
|
||||||
|
|
||||||
edges = {}
|
|
||||||
for edge in mesh_buffer.edges:
|
|
||||||
e = {}
|
|
||||||
e["verts"] = [edge.verts[0].index, edge.verts[1].index]
|
|
||||||
|
|
||||||
# Edge metadata
|
|
||||||
e["smooth"] = edge.smooth
|
|
||||||
|
|
||||||
edges[edge.index] = e
|
|
||||||
mesh_data["edges"] = edges
|
|
||||||
|
|
||||||
faces = {}
|
|
||||||
for face in mesh_buffer.faces:
|
|
||||||
f = {}
|
|
||||||
fverts = []
|
|
||||||
for vert in face.verts:
|
|
||||||
fverts.append(vert.index)
|
|
||||||
|
|
||||||
f["verts"] = fverts
|
|
||||||
f["material_index"] = face.material_index
|
|
||||||
|
|
||||||
uvs = []
|
|
||||||
# Face metadata
|
|
||||||
for loop in face.loops:
|
|
||||||
loop_uv = loop[uv_layer]
|
|
||||||
|
|
||||||
uvs.append(list(loop_uv.uv))
|
|
||||||
|
|
||||||
f["uv"] = uvs
|
|
||||||
faces[face.index] = f
|
|
||||||
|
|
||||||
mesh_data["faces"] = faces
|
|
||||||
|
|
||||||
uv_layers = []
|
|
||||||
for uv_layer in mesh.uv_layers:
|
|
||||||
uv_layers.append(uv_layer.name)
|
|
||||||
|
|
||||||
mesh_data["uv_layers"] = uv_layers
|
|
||||||
return mesh_data
|
|
||||||
|
|
||||||
|
|
||||||
def init_client(key=None):
|
|
||||||
client_dict = {}
|
|
||||||
|
|
||||||
C = bpy.context
|
|
||||||
Net = C.window_manager.session
|
|
||||||
client_dict['uuid'] = str(uuid4())
|
|
||||||
client_dict['location'] = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
|
|
||||||
client_dict['color'] = [Net.client_color.r,
|
|
||||||
Net.client_color.g, Net.client_color.b, 1]
|
|
||||||
|
|
||||||
client_dict['active_objects'] = get_selected_objects(C.view_layer)
|
|
||||||
|
|
||||||
return client_dict
|
|
BIN
img/2users.mp4
BIN
img/2users.mp4
Binary file not shown.
BIN
img/4users.gif
BIN
img/4users.gif
Binary file not shown.
Before Width: | Height: | Size: 1.5 MiB |
@ -1 +0,0 @@
|
|||||||
<mxfile modified="2019-06-25T09:18:02.438Z" host="www.draw.io" agent="Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/9.3.1 Chrome/66.0.3359.181 Electron/3.0.6 Safari/537.36" etag="hxPcua1ZelLGi1k5iccK" version="10.8.0" type="device"><diagram id="4DjPBCs2o4pktraMiBBA" name="Page-1">7VpZc+I4EP41VO0+JGVbPuCRQMhkd47M5pynKWML8I6xWFkQmF+/kiXZlmVzDLAkm5CqlPWpdbW6v27JboHedHmF/dnkEwph3LKMcNkC/ZZluUaH/mfAigN2x+TAGEchh0rAbfQTCtAQ6DwKYaoIEoRiEs1UMEBJAgOiYD7G6FkVG6FYHXXmj6EG3AZ+rKOPUUgmHG1bXoF/gNF4Ikc2XbHgqS+FxUrSiR+i5xIELlughxEi/Gm67MGY6U7qhbcbNNTmE8MwIds0WETGQ/ynN5suegv3kQzunm7uz0zRTUpWcsUwpAoQRYTJBI1R4seXBXqB0TwJIevWoKVC5iNCMwqaFPwbErISu+nPCaLQhExjUUtnjFdPrP25a7Yl8C0DDGoxAugvxRC8tCqXbiCOppBALEBdG9JafDyGZI0KAJdjyy41FDq8goiOgldUAMPYJ9FCtQtfmNc4lxNNuxj7q5LADEUJSUs93zCACghHcSxhN8JPTFEWu0kfeI/1rW0TnDu17fMJpGiOAyjaKR2XVllAmfHsYEjSyhd+PBcq6t9/utGsi8AlUY0BwzT66Q8zAbaTQlNU2rloOX2K+HE0TigQ0L1lG36xgJhE1Ee7omIahWFmmbE/hPGFH/wYZzbaQzHC2bhglP1qDWWtY7Ch4LKOasSUFW9WDEa0Ms5tr7q5vLSbRWmbfmZU9hyoPaDRKIX7bva8P3n4o3s9vPv86N7D9oPjzr+egfZJWGMZkSfJAfSZ84UjSgVZsILCFU+FYM4zGzgmpbRBuix+UCBBCZTYIGKqEi1CKRHEfppGAQeFCJvyCCWkZISDgUt/uRFWKGcjfdXuhX0IttJsC1BCsdqOZ9r8PwAnZRfpjAW5dG+uNRtULex5EhF4O/MDVvtMkxPVmho1rnl8o2cDS/U/yxAk+FzKFAQ0KSUJjtG8HYrmdvZL+8TRXPEx83/jY9zaD+9k0hBkbmxUDKPBq3bNLYBdP85gS3ngrpen6fA6eTV3OVQMknM8ka2bSjQ5t5zXYuzcptZlcls6BTiIU+ycJ3cqtiw4uMk2q/LemrT6YLmwFq0+X961LDdmme8Q06cxyffspPGrXckg7ZNHMOukmeW5J9PJb6Wq+tTyyB5diqpmhWyMTWSz5oR8EIoA21LEQY7Suk/bVCd2KT1Vs7BOba3snk/6aJkq0Hz/9vKv6+7HF+j+dlulxpOnrzpvajpKJ/6MPQarOKLKwpsVNeRa/TjMgfx64Muc0F6gotGa876m5GZCNSsatXSNghqN2kejU/fV0GmJ76zXeVQv02bzUX2b48a+Z/q9bMbWvPCxe9f70P9ydRwO28vjTO+FcZi8KHkRHmf8mse9moP7Ro+zalyuOWz/12cZ0K5kLt76c7ZjGOvkj3POtnQ+kDzAr8AtY4hwFoppnfvPnL3PujCLR8UZ83q2FEcRKjxGgqJZl1ZKeZ7I5q5cU8UncxagOPZnKeQyeUmVEh3MlpktxVQPdMvHw98MJmdRfRmlp9/zxsxwz9LMF/kEWAfFSiQ1CiUNUbjSQKwhbGz5oqPoTbzyaOydTYWvD6kbQB3KyH4bdLzVWlJ6lPDj71Eih6WWxEdWZ0Nhto6DrGyoqegEvTOwVrJuUxnOPaIhOOrvvlKC0Q9YIsHAYH9sXyhPSlxQLKKRchRnlDrKWHQDg+6XylbutkFNYPUcPbBaRzscdN556K3zUALJdzQn7yz0VljIsr3qO+46HqpJ8I/GQ8A7bYJv/dKRuu3tdKauvUB8PWk/2PbbH+sUab8tX9Nu+XoNdNrr5I+T9ksVvofbtxtuRdr/HnHfUMS1zReW94O6vH+fW8djHpps9ULH03Vn1+hOfk53+KvcOhJ/qboz1KjY7mi6M62aRM/d3fBosfjsmgfM4tt1cPkv</diagram></mxfile>
|
|
Binary file not shown.
Before Width: | Height: | Size: 15 KiB |
File diff suppressed because one or more lines are too long
BIN
img/v0.0.5.png
BIN
img/v0.0.5.png
Binary file not shown.
Before Width: | Height: | Size: 72 KiB |
126
libs/debug.py
Normal file
126
libs/debug.py
Normal file
@ -0,0 +1,126 @@
|
|||||||
|
import bpy
|
||||||
|
import bgl
|
||||||
|
import gpu
|
||||||
|
from gpu_extras.batch import batch_for_shader
|
||||||
|
import numpy
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_COORDS = [(0.0, 0.0, 0.0)]
|
||||||
|
DEFAULT_INDICES = [(0)]
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_viewport():
|
||||||
|
bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
|
||||||
|
|
||||||
|
|
||||||
|
class Drawable():
|
||||||
|
"""Drawable base class in charge to hanfle the drawing pipline.
|
||||||
|
|
||||||
|
:param coords: list of vertices
|
||||||
|
:type coords: list of tuples. ex: [(x,y,z),...]
|
||||||
|
:param indices: list of vertices index to structure geometry
|
||||||
|
:type indices: list of tuples.
|
||||||
|
:param location: suited location in world space.
|
||||||
|
:type location: tuple, (x,y,z)
|
||||||
|
:param mode: primitive drawing mode.
|
||||||
|
:type mode: string in ['POINTS','LINES','TRIS'], default: "POINTS".
|
||||||
|
:param color: primitive color
|
||||||
|
:type color: tuple, (r,g,b,a)
|
||||||
|
:param duration: lifetime of the primitive in seconds
|
||||||
|
:type duration: float
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, coords=DEFAULT_COORDS, indices=DEFAULT_INDICES, location=(0.0, 0.0, 0.0), mode='POINTS', color=(1, 0, 0, 1), duration=0):
|
||||||
|
self._duration = duration
|
||||||
|
self._color = color
|
||||||
|
self._coord = [tuple(numpy.add(c,location)) for c in coords]
|
||||||
|
self.shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')
|
||||||
|
self.batch = batch_for_shader(
|
||||||
|
self.shader, mode, {"pos": self._coord}, indices=indices)
|
||||||
|
|
||||||
|
# Bind the drawing function
|
||||||
|
self._handler = bpy.types.SpaceView3D.draw_handler_add(
|
||||||
|
self.draw, (), 'WINDOW', 'POST_VIEW')
|
||||||
|
# Bind the callback
|
||||||
|
if duration:
|
||||||
|
self._timer = bpy.app.timers.register(
|
||||||
|
self.clear, first_interval=duration)
|
||||||
|
|
||||||
|
def draw(self):
|
||||||
|
self.shader.bind()
|
||||||
|
self.shader.uniform_float("color", self._color)
|
||||||
|
self.batch.draw(self.shader)
|
||||||
|
|
||||||
|
def clear(self):
|
||||||
|
"""Remove the drawable object from the viewport
|
||||||
|
"""
|
||||||
|
bpy.types.SpaceView3D.draw_handler_remove(self._handler, 'WINDOW')
|
||||||
|
|
||||||
|
|
||||||
|
def draw_point(location=(0, 0, 0), color=(1, 0, 0, 1), duration=1):
|
||||||
|
"""Draw a point
|
||||||
|
|
||||||
|
:param location: suited location in world space.
|
||||||
|
:type location: tuple, (x,y,z)
|
||||||
|
:param color: primitive color
|
||||||
|
:type color: tuple, (r,g,b,a)
|
||||||
|
:param duration: lifetime of the primitive in seconds
|
||||||
|
:type duration: float
|
||||||
|
"""
|
||||||
|
return Drawable(location=location, color=color, duration=duration)
|
||||||
|
|
||||||
|
|
||||||
|
def draw_line(a=(0, 0, 0), b=(0, 1, 0), color=(1, 0, 0, 1), duration=1):
|
||||||
|
""" Draw a line from a given point A to the point B.
|
||||||
|
|
||||||
|
:param a: point A location in world space.
|
||||||
|
:type a: tuple, (x,y,z)
|
||||||
|
:param b: point B location in world space.
|
||||||
|
:type b: tuple, (x,y,z)
|
||||||
|
:param color: primitive color
|
||||||
|
:type color: tuple, (r,g,b,a)
|
||||||
|
:param duration: lifetime of the primitive in seconds
|
||||||
|
:type duration: float
|
||||||
|
"""
|
||||||
|
return Drawable(coords=[a, b], indices=[(0, 1)], mode='LINES', color=color, duration=duration)
|
||||||
|
|
||||||
|
|
||||||
|
def draw_cube(radius=1, location=(0, 0, 0), color=(1, 0, 0, 1), duration=1):
|
||||||
|
""" Draw a cube.
|
||||||
|
|
||||||
|
:param radius: size of the cube.
|
||||||
|
:type radius: float
|
||||||
|
:param location: suited location in world space.
|
||||||
|
:type location: tuple, (x,y,z)
|
||||||
|
:param color: primitive color
|
||||||
|
:type color: tuple, (r,g,b,a)
|
||||||
|
:param duration: lifetime of the primitive in seconds
|
||||||
|
:type duration: float
|
||||||
|
"""
|
||||||
|
coords = (
|
||||||
|
(-radius, -radius, -radius), (+radius, -radius, -radius),
|
||||||
|
(-radius, +radius, -radius), (+radius, +radius, -radius),
|
||||||
|
(-radius, -radius, +radius), (+radius, -radius, +radius),
|
||||||
|
(-radius, +radius, +radius), (+radius, +radius, +radius))
|
||||||
|
|
||||||
|
indices = (
|
||||||
|
(0, 1), (0, 2), (1, 3), (2, 3),
|
||||||
|
(4, 5), (4, 6), (5, 7), (6, 7),
|
||||||
|
(0, 4), (1, 5), (2, 6), (3, 7))
|
||||||
|
|
||||||
|
return Drawable(coords=coords, mode='LINES', indices=indices, location=location, color=color, duration=duration)
|
||||||
|
|
||||||
|
def draw_custom(coords=DEFAULT_COORDS, indices=DEFAULT_INDICES, mode='LINES',location=(0, 0, 0), color=(1, 0, 0, 1), duration=1):
|
||||||
|
""" Draw a user defined polygon shape.
|
||||||
|
|
||||||
|
:param coords: list of vertices
|
||||||
|
:type coords: list of tuples. ex: [(x,y,z),...]
|
||||||
|
:param indices: list of vertices index to structure geometry
|
||||||
|
:type indices: list of tuples.
|
||||||
|
:param location: suited location in
|
||||||
|
:param color: primitive color
|
||||||
|
:type color: tuple, (r,g,b,a)
|
||||||
|
:param duration: lifetime of the primitive in seconds
|
||||||
|
:type duration: float
|
||||||
|
"""
|
||||||
|
return Drawable(coords=coords, indices=indices, mode=mode, location=location, color=color, duration=duration)
|
@ -350,6 +350,17 @@ def dump(any, depth=1):
|
|||||||
dumper.depath = depth
|
dumper.depath = depth
|
||||||
return dumper.dump(any)
|
return dumper.dump(any)
|
||||||
|
|
||||||
|
def dump_datablock(datablock, depth):
|
||||||
|
if datablock:
|
||||||
|
dumper = Dumper()
|
||||||
|
dumper.type_subset = dumper.match_subset_all
|
||||||
|
dumper.depth = depth
|
||||||
|
|
||||||
|
datablock_type = datablock.bl_rna.name
|
||||||
|
key = "{}/{}".format(datablock_type, datablock.name)
|
||||||
|
data = dumper.dump(datablock)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
def load(dst, src):
|
def load(dst, src):
|
||||||
loader = Loader()
|
loader = Loader()
|
||||||
|
1
libs/replication
Submodule
1
libs/replication
Submodule
Submodule libs/replication added at e56b847a92
76
message.py
76
message.py
@ -1,76 +0,0 @@
|
|||||||
import logging
|
|
||||||
try:
|
|
||||||
from .libs import umsgpack
|
|
||||||
|
|
||||||
except:
|
|
||||||
# Server import
|
|
||||||
from libs import umsgpack
|
|
||||||
|
|
||||||
import zmq
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
logger.setLevel(logging.ERROR)
|
|
||||||
|
|
||||||
|
|
||||||
class Message(object):
|
|
||||||
"""
|
|
||||||
Message is formatted on wire as 2 frames:
|
|
||||||
frame 0: key (0MQ string) // property path
|
|
||||||
frame 1: id (0MQ string) // property path
|
|
||||||
frame 3: body (blob) // Could be any data
|
|
||||||
|
|
||||||
"""
|
|
||||||
key = None # key (string)
|
|
||||||
id = None # User (string)
|
|
||||||
body = None # data blob
|
|
||||||
|
|
||||||
|
|
||||||
def __init__(self, key=None, id=None, body=None):
|
|
||||||
self.key = key
|
|
||||||
self.body = body
|
|
||||||
self.id = id
|
|
||||||
|
|
||||||
def store(self, dikt):
|
|
||||||
"""Store me in a dict if I have anything to store"""
|
|
||||||
# this currently erasing old value
|
|
||||||
if self.key is not None:
|
|
||||||
if self.body == 'None':
|
|
||||||
logger.info("erasing key {}".format(self.key))
|
|
||||||
del dikt[self.key]
|
|
||||||
else:
|
|
||||||
dikt[self.key] = self
|
|
||||||
|
|
||||||
def send(self, socket):
|
|
||||||
"""Send key-value message to socket; any empty frames are sent as such."""
|
|
||||||
key = ''.encode() if self.key is None else self.key.encode()
|
|
||||||
body = umsgpack.packb('None') if self.body is None else umsgpack.packb(self.body)
|
|
||||||
id = ''.encode() if self.id is None else self.id
|
|
||||||
|
|
||||||
try:
|
|
||||||
socket.send_multipart([key, id, body])
|
|
||||||
except:
|
|
||||||
print("Fail to send {} {} {}".format(key, id, body))
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def recv(cls, socket):
|
|
||||||
"""Reads key-value message from socket, returns new kvmsg instance."""
|
|
||||||
key, id, body = socket.recv_multipart(zmq.NOBLOCK)
|
|
||||||
key = key.decode() if key else None
|
|
||||||
id = id if id else None
|
|
||||||
body = umsgpack.unpackb(body) if body else None
|
|
||||||
|
|
||||||
return cls(key=key, id=id, body=body)
|
|
||||||
|
|
||||||
def dump(self):
|
|
||||||
if self.body is None:
|
|
||||||
size = 0
|
|
||||||
data = 'NULL'
|
|
||||||
else:
|
|
||||||
size = len(self.body)
|
|
||||||
data = repr(self.body)
|
|
||||||
print("[key:{key}][size:{size}] {data}".format(
|
|
||||||
key=self.key,
|
|
||||||
size=size,
|
|
||||||
data=data,
|
|
||||||
))
|
|
||||||
|
|
525
operators.py
525
operators.py
@ -1,205 +1,150 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import queue
|
||||||
import random
|
import random
|
||||||
import string
|
import string
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
import queue
|
|
||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import bpy
|
import bpy
|
||||||
from bpy_extras.io_utils import ExportHelper
|
|
||||||
import mathutils
|
import mathutils
|
||||||
from pathlib import Path
|
from bpy_extras.io_utils import ExportHelper
|
||||||
from bpy.app.handlers import persistent
|
|
||||||
|
|
||||||
from . import environment, client, draw, helpers, ui
|
from . import environment, presence, ui, utils, delayable
|
||||||
from .libs import umsgpack
|
from .libs import umsgpack
|
||||||
|
from .libs.replication.data import ReplicatedDataFactory
|
||||||
|
from .libs.replication.interface import Client
|
||||||
|
from . import bl_types
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.setLevel(logging.DEBUG)
|
logger.setLevel(logging.DEBUG)
|
||||||
|
|
||||||
# client_instance = None
|
client = None
|
||||||
|
delayables = []
|
||||||
|
ui_context = None
|
||||||
|
|
||||||
server = None
|
def add_datablock(datablock):
|
||||||
context = None
|
global client
|
||||||
execution_queue = queue.Queue()
|
child = []
|
||||||
|
|
||||||
# This function can savely be called in another thread.
|
if hasattr(datablock, "data"):
|
||||||
# The function will be executed when the timer runs the next time.
|
child.append(add_datablock(datablock.data))
|
||||||
|
if hasattr(datablock, "materials"):
|
||||||
|
for mat in datablock.materials:
|
||||||
def run_in_main_thread(function, args):
|
child.append(add_datablock(mat))
|
||||||
execution_queue.put(function)
|
if hasattr(datablock, "collection") and hasattr(datablock.collection, "children"):
|
||||||
|
for coll in datablock.collection.children:
|
||||||
|
child.append(add_datablock(coll))
|
||||||
def execute_queued_functions():
|
if hasattr(datablock, "children"):
|
||||||
while not execution_queue.empty():
|
for coll in datablock.children:
|
||||||
function, args = execution_queue.get()
|
child.append(add_datablock(coll))
|
||||||
function(args[0], args[1])
|
if hasattr(datablock, "objects"):
|
||||||
return .1
|
for obj in datablock.objects:
|
||||||
|
child.append(add_datablock(obj))
|
||||||
|
if hasattr(datablock,'uuid') and datablock.uuid and client.exist(datablock.uuid):
|
||||||
def clean_scene(elements=environment.get_replicated_types()):
|
return datablock.uuid
|
||||||
for datablock in elements:
|
|
||||||
datablock_ref = getattr(bpy.data, helpers.BPY_TYPES[datablock])
|
|
||||||
for item in datablock_ref:
|
|
||||||
try:
|
|
||||||
datablock_ref.remove(item)
|
|
||||||
# Catch last scene remove
|
|
||||||
except RuntimeError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def upload_client_instance_position():
|
|
||||||
username = bpy.context.window_manager.session.username
|
|
||||||
if client.instance:
|
|
||||||
|
|
||||||
key = "Client/{}".format(username)
|
|
||||||
|
|
||||||
current_coords = draw.get_client_view_rect()
|
|
||||||
client_list = client.instance.get(key)
|
|
||||||
|
|
||||||
if current_coords and client_list:
|
|
||||||
if current_coords != client_list[0][1]['location']:
|
|
||||||
client_list[0][1]['location'] = current_coords
|
|
||||||
client.instance.set(key, client_list[0][1])
|
|
||||||
|
|
||||||
|
|
||||||
def update_client_selected_object(context):
|
|
||||||
session = bpy.context.window_manager.session
|
|
||||||
username = bpy.context.window_manager.session.username
|
|
||||||
client_key = "Client/{}".format(username)
|
|
||||||
client_data = client.instance.get(client_key)
|
|
||||||
|
|
||||||
selected_objects = helpers.get_selected_objects(context.scene)
|
|
||||||
if len(selected_objects) > 0 and len(client_data) > 0:
|
|
||||||
|
|
||||||
for obj in selected_objects:
|
|
||||||
# if obj not in client_data[0][1]['active_objects']:
|
|
||||||
client_data[0][1]['active_objects'] = selected_objects
|
|
||||||
|
|
||||||
client.instance.set(client_key, client_data[0][1])
|
|
||||||
break
|
|
||||||
|
|
||||||
elif client_data and client_data[0][1]['active_objects']:
|
|
||||||
client_data[0][1]['active_objects'] = []
|
|
||||||
client.instance.set(client_key, client_data[0][1])
|
|
||||||
|
|
||||||
|
|
||||||
def init_datablocks():
|
|
||||||
session = bpy.context.window_manager.session
|
|
||||||
environment.genererate_replicated_types()
|
|
||||||
for datatype in environment.rtypes:
|
|
||||||
if session.supported_datablock[datatype].is_replicated:
|
|
||||||
logger.debug("INIT: {}".format(datatype))
|
|
||||||
for item in getattr(bpy.data, helpers.BPY_TYPES[datatype]):
|
|
||||||
|
|
||||||
key = "{}/{}".format(datatype, item.name)
|
|
||||||
|
|
||||||
if item.id != 'None' and not session.reset_rights:
|
|
||||||
client.instance.set(key,id=session.reset_rights)
|
|
||||||
else:
|
else:
|
||||||
item.id = bpy.context.window_manager.session.username
|
new_uuid = client.add(datablock, childs=child)
|
||||||
client.instance.set(key)
|
datablock.uuid = new_uuid
|
||||||
|
return new_uuid
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: cleanup
|
||||||
|
def init_supported_datablocks(supported_types_id):
|
||||||
|
global client
|
||||||
|
|
||||||
def default_tick():
|
for type_id in supported_types_id:
|
||||||
upload_client_instance_position()
|
if hasattr(bpy.data, type_id):
|
||||||
|
for item in getattr(bpy.data, type_id):
|
||||||
return .1
|
add_datablock(item)
|
||||||
|
|
||||||
|
|
||||||
def register_ticks():
|
|
||||||
# REGISTER Updaters
|
|
||||||
bpy.app.timers.register(default_tick)
|
|
||||||
bpy.app.timers.register(execute_queued_functions)
|
|
||||||
|
|
||||||
|
|
||||||
def unregister_ticks():
|
|
||||||
# REGISTER Updaters
|
|
||||||
try:
|
|
||||||
bpy.app.timers.unregister(default_tick)
|
|
||||||
bpy.app.timers.unregister(execute_queued_functions)
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# OPERATORS
|
# OPERATORS
|
||||||
|
class SessionStartOperator(bpy.types.Operator):
|
||||||
|
bl_idname = "session.start"
|
||||||
class SessionJoinOperator(bpy.types.Operator):
|
bl_label = "start"
|
||||||
bl_idname = "session.join"
|
|
||||||
bl_label = "join"
|
|
||||||
bl_description = "connect to a net server"
|
bl_description = "connect to a net server"
|
||||||
bl_options = {"REGISTER"}
|
bl_options = {"REGISTER"}
|
||||||
|
|
||||||
|
host: bpy.props.BoolProperty(default=False)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def poll(cls, context):
|
def poll(cls, context):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def execute(self, context):
|
def execute(self, context):
|
||||||
global execution_queue
|
global client, delayables
|
||||||
net_settings = context.window_manager.session
|
settings = context.window_manager.session
|
||||||
# save config
|
# save config
|
||||||
net_settings.save(context)
|
settings.save(context)
|
||||||
|
|
||||||
# Scene setup
|
# Scene setup
|
||||||
if net_settings.start_empty:
|
if settings.start_empty:
|
||||||
clean_scene()
|
utils.clean_scene()
|
||||||
|
|
||||||
# Session setup
|
bpy_factory = ReplicatedDataFactory()
|
||||||
if net_settings.username == "DefaultUser":
|
supported_bl_types = []
|
||||||
net_settings.username = "{}_{}".format(
|
|
||||||
net_settings.username, randomStringDigits())
|
|
||||||
|
|
||||||
username = str(context.window_manager.session.username)
|
# init the factory with supported types
|
||||||
|
for type in bl_types.types_to_register():
|
||||||
|
_type = getattr(bl_types, type)
|
||||||
|
supported_bl_types.append(_type.bl_id)
|
||||||
|
|
||||||
if len(net_settings.ip) < 1:
|
bpy_factory.register_type(_type.bl_class, _type.bl_rep_class, timer=_type.bl_delay_refresh,automatic=True)
|
||||||
net_settings.ip = "127.0.0.1"
|
|
||||||
|
|
||||||
client.instance = client.Client(execution_queue)
|
if _type.bl_delay_apply > 0:
|
||||||
client.instance.connect(net_settings.username,
|
delayables.append(delayable.ApplyTimer(timout=_type.bl_delay_apply,target_type=_type.bl_rep_class))
|
||||||
net_settings.ip,
|
|
||||||
net_settings.port)
|
|
||||||
|
|
||||||
# net_settings.is_running = True
|
client = Client(factory=bpy_factory)
|
||||||
# bpy.ops.session.refresh()
|
|
||||||
register_ticks()
|
if self.host:
|
||||||
|
client.host(
|
||||||
|
id=settings.username,
|
||||||
|
address=settings.ip,
|
||||||
|
port=settings.port
|
||||||
|
)
|
||||||
|
|
||||||
|
if settings.init_scene:
|
||||||
|
init_supported_datablocks(supported_bl_types)
|
||||||
|
else:
|
||||||
|
client.connect(
|
||||||
|
id=settings.username,
|
||||||
|
address=settings.ip,
|
||||||
|
port=settings.port
|
||||||
|
)
|
||||||
|
|
||||||
|
usr = presence.User(
|
||||||
|
username=settings.username,
|
||||||
|
color=(settings.client_color.r,
|
||||||
|
settings.client_color.g,
|
||||||
|
settings.client_color.b,
|
||||||
|
1),
|
||||||
|
)
|
||||||
|
|
||||||
|
settings.user_uuid = client.add(usr)
|
||||||
|
delayables.append(delayable.ClientUpdate(client_uuid=settings.user_uuid))
|
||||||
|
|
||||||
|
# Push all added values
|
||||||
|
client.push()
|
||||||
|
|
||||||
# Launch drawing module
|
# Launch drawing module
|
||||||
if net_settings.enable_presence:
|
if settings.enable_presence:
|
||||||
draw.renderer.run()
|
presence.renderer.run()
|
||||||
|
|
||||||
|
for d in delayables:
|
||||||
|
d.register()
|
||||||
|
|
||||||
return {"FINISHED"}
|
return {"FINISHED"}
|
||||||
|
|
||||||
|
|
||||||
class SessionPropertyAddOperator(bpy.types.Operator):
|
class SessionStopOperator(bpy.types.Operator):
|
||||||
bl_idname = "session.add_prop"
|
bl_idname = "session.stop"
|
||||||
bl_label = "add"
|
bl_label = "close"
|
||||||
bl_description = "broadcast a property to connected client_instances"
|
bl_description = "stop net service"
|
||||||
bl_options = {"REGISTER"}
|
|
||||||
|
|
||||||
property_path: bpy.props.StringProperty(default="None")
|
|
||||||
depth: bpy.props.IntProperty(default=1)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def poll(cls, context):
|
|
||||||
return True
|
|
||||||
|
|
||||||
def execute(self, context):
|
|
||||||
|
|
||||||
client.instance.add(self.property_path)
|
|
||||||
|
|
||||||
return {"FINISHED"}
|
|
||||||
|
|
||||||
|
|
||||||
class SessionPropertyGetOperator(bpy.types.Operator):
|
|
||||||
bl_idname = "session.get_prop"
|
|
||||||
bl_label = "get"
|
|
||||||
bl_description = "broadcast a property to connected client_instances"
|
|
||||||
bl_options = {"REGISTER"}
|
bl_options = {"REGISTER"}
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -207,9 +152,16 @@ class SessionPropertyGetOperator(bpy.types.Operator):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def execute(self, context):
|
def execute(self, context):
|
||||||
global client_instance
|
global client, delayables
|
||||||
|
|
||||||
client.instance.get("client")
|
assert(client)
|
||||||
|
|
||||||
|
client.disconnect()
|
||||||
|
|
||||||
|
for d in delayables:
|
||||||
|
d.unregister()
|
||||||
|
|
||||||
|
presence.renderer.stop()
|
||||||
|
|
||||||
return {"FINISHED"}
|
return {"FINISHED"}
|
||||||
|
|
||||||
@ -227,85 +179,15 @@ class SessionPropertyRemoveOperator(bpy.types.Operator):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def execute(self, context):
|
def execute(self, context):
|
||||||
|
global client
|
||||||
try:
|
try:
|
||||||
del client.instance.property_map[self.property_path]
|
client.remove(self.property_path)
|
||||||
|
|
||||||
return {"FINISHED"}
|
return {"FINISHED"}
|
||||||
except:
|
except:
|
||||||
return {"CANCELED"}
|
return {"CANCELED"}
|
||||||
|
|
||||||
|
|
||||||
class SessionHostOperator(bpy.types.Operator):
|
|
||||||
bl_idname = "session.create"
|
|
||||||
bl_label = "create"
|
|
||||||
bl_description = "create to a net session"
|
|
||||||
bl_options = {"REGISTER"}
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def poll(cls, context):
|
|
||||||
return True
|
|
||||||
|
|
||||||
def execute(self, context):
|
|
||||||
global server
|
|
||||||
|
|
||||||
net_settings = context.window_manager.session
|
|
||||||
|
|
||||||
script_dir = os.path.join(os.path.dirname(
|
|
||||||
os.path.abspath(__file__)), "server.py")
|
|
||||||
|
|
||||||
python_path = Path(bpy.app.binary_path_python)
|
|
||||||
cwd_for_subprocesses = python_path.parent
|
|
||||||
|
|
||||||
server = subprocess.Popen(
|
|
||||||
[str(python_path), script_dir], shell=False, stdout=subprocess.PIPE)
|
|
||||||
|
|
||||||
bpy.ops.session.join()
|
|
||||||
|
|
||||||
if net_settings.init_scene:
|
|
||||||
init_datablocks()
|
|
||||||
|
|
||||||
net_settings.is_admin = True
|
|
||||||
|
|
||||||
return {"FINISHED"}
|
|
||||||
|
|
||||||
|
|
||||||
class SessionStopOperator(bpy.types.Operator):
|
|
||||||
bl_idname = "session.stop"
|
|
||||||
bl_label = "close"
|
|
||||||
bl_description = "stop net service"
|
|
||||||
bl_options = {"REGISTER"}
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def poll(cls, context):
|
|
||||||
return True
|
|
||||||
|
|
||||||
def execute(self, context):
|
|
||||||
global server
|
|
||||||
|
|
||||||
net_settings = context.window_manager.session
|
|
||||||
|
|
||||||
if server:
|
|
||||||
server.kill()
|
|
||||||
time.sleep(0.25)
|
|
||||||
|
|
||||||
server = None
|
|
||||||
|
|
||||||
if client.instance:
|
|
||||||
client.instance.exit()
|
|
||||||
time.sleep(0.25)
|
|
||||||
# del client_instance
|
|
||||||
|
|
||||||
# client_instance = None
|
|
||||||
net_settings.is_admin = False
|
|
||||||
|
|
||||||
unregister_ticks()
|
|
||||||
draw.renderer.stop()
|
|
||||||
else:
|
|
||||||
logger.debug("No server/client_instance running.")
|
|
||||||
|
|
||||||
return {"FINISHED"}
|
|
||||||
|
|
||||||
|
|
||||||
class SessionPropertyRightOperator(bpy.types.Operator):
|
class SessionPropertyRightOperator(bpy.types.Operator):
|
||||||
bl_idname = "session.right"
|
bl_idname = "session.right"
|
||||||
bl_label = "Change owner to"
|
bl_label = "Change owner to"
|
||||||
@ -324,28 +206,18 @@ class SessionPropertyRightOperator(bpy.types.Operator):
|
|||||||
|
|
||||||
def draw(self, context):
|
def draw(self, context):
|
||||||
layout = self.layout
|
layout = self.layout
|
||||||
net_settings = context.window_manager.session
|
settings = context.window_manager.session
|
||||||
|
|
||||||
col = layout.column()
|
col = layout.column()
|
||||||
col.prop(net_settings, "clients")
|
col.prop(settings, "clients")
|
||||||
|
|
||||||
def execute(self, context):
|
def execute(self, context):
|
||||||
global server
|
settings = context.window_manager.session
|
||||||
|
global client
|
||||||
|
|
||||||
net_settings = context.window_manager.session
|
if client:
|
||||||
|
client.right(self.key,settings.clients)
|
||||||
|
|
||||||
if net_settings.is_admin:
|
|
||||||
val = client.instance.get(self.key)
|
|
||||||
val[0][1]['id'] = net_settings.clients
|
|
||||||
|
|
||||||
client.instance.set(key=self.key, value=val[0][1], override=True)
|
|
||||||
item = helpers.resolve_bpy_path(self.key)
|
|
||||||
if item:
|
|
||||||
item.id = net_settings.clients
|
|
||||||
logger.info("Updating {} rights to {}".format(
|
|
||||||
self.key, net_settings.clients))
|
|
||||||
else:
|
|
||||||
print("Not admin")
|
|
||||||
|
|
||||||
return {"FINISHED"}
|
return {"FINISHED"}
|
||||||
|
|
||||||
@ -363,12 +235,12 @@ class SessionSnapUserOperator(bpy.types.Operator):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def execute(self, context):
|
def execute(self, context):
|
||||||
area, region, rv3d = draw.view3d_find()
|
area, region, rv3d = presence.view3d_find()
|
||||||
|
global client
|
||||||
|
|
||||||
target_client = client.instance.get(
|
target_client = client.get(self.target_client)
|
||||||
"Client/{}".format(self.target_client))
|
|
||||||
if target_client:
|
if target_client:
|
||||||
rv3d.view_location = target_client[0][1]['location'][0]
|
rv3d.view_location = target_client.buffer['location'][0]
|
||||||
rv3d.view_distance = 30.0
|
rv3d.view_distance = 30.0
|
||||||
|
|
||||||
return {"FINISHED"}
|
return {"FINISHED"}
|
||||||
@ -378,177 +250,52 @@ class SessionSnapUserOperator(bpy.types.Operator):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class SessionDumpDatabase(bpy.types.Operator, ExportHelper):
|
class SessionApply(bpy.types.Operator):
|
||||||
bl_idname = "session.dump"
|
bl_idname = "session.apply"
|
||||||
bl_label = "dump json data"
|
bl_label = "apply the target item into the blender data"
|
||||||
bl_description = "dump session stored data to a json file"
|
bl_description = "Apply target object into blender data"
|
||||||
bl_options = {"REGISTER"}
|
bl_options = {"REGISTER"}
|
||||||
|
|
||||||
# ExportHelper mixin class uses this
|
target = bpy.props.StringProperty()
|
||||||
filename_ext = ".json"
|
|
||||||
|
|
||||||
filter_glob: bpy.props.StringProperty(
|
|
||||||
default="*.json",
|
|
||||||
options={'HIDDEN'},
|
|
||||||
maxlen=255, # Max internal buffer length, longer would be clamped.
|
|
||||||
)
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def poll(cls, context):
|
def poll(cls, context):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def execute(self, context):
|
def execute(self, context):
|
||||||
print(self.filepath)
|
global client
|
||||||
if client.instance and client.instance.state() == 3:
|
|
||||||
client.instance.dump(self.filepath)
|
client.apply(uuid=self.target)
|
||||||
|
|
||||||
return {"FINISHED"}
|
return {"FINISHED"}
|
||||||
|
|
||||||
return {"CANCELLED"}
|
|
||||||
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class SessionSaveConfig(bpy.types.Operator):
|
|
||||||
bl_idname = "session.save"
|
|
||||||
bl_label = "Save session configuration"
|
|
||||||
bl_description = "Save session configuration"
|
|
||||||
bl_options = {"REGISTER"}
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def poll(cls, context):
|
|
||||||
return True
|
|
||||||
|
|
||||||
def execute(self, context):
|
|
||||||
context.window_manager.session.save()
|
|
||||||
|
|
||||||
|
|
||||||
classes = (
|
classes = (
|
||||||
SessionJoinOperator,
|
SessionStartOperator,
|
||||||
SessionPropertyAddOperator,
|
|
||||||
SessionPropertyGetOperator,
|
|
||||||
SessionStopOperator,
|
SessionStopOperator,
|
||||||
SessionHostOperator,
|
|
||||||
SessionPropertyRemoveOperator,
|
SessionPropertyRemoveOperator,
|
||||||
SessionSnapUserOperator,
|
SessionSnapUserOperator,
|
||||||
SessionPropertyRightOperator,
|
SessionPropertyRightOperator,
|
||||||
SessionDumpDatabase,
|
SessionApply,
|
||||||
SessionSaveConfig,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def is_replicated(update):
|
|
||||||
object_type = update.id.bl_rna.__class__.__name__
|
|
||||||
object_name = update.id.name
|
|
||||||
|
|
||||||
# Master collection special cae
|
|
||||||
if update.id.name == 'Master Collection':
|
|
||||||
object_type = 'Scene'
|
|
||||||
object_name = bpy.context.scene.name
|
|
||||||
if 'Light' in update.id.bl_rna.name:
|
|
||||||
object_type = 'Light'
|
|
||||||
|
|
||||||
key = "{}/{}".format(object_type, object_name)
|
|
||||||
|
|
||||||
if client.instance.exist(key):
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
logger.debug("{} Not rep".format(key))
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def get_datablock_from_update(update, context):
|
|
||||||
item_type = update.id.__class__.__name__
|
|
||||||
item_id = update.id.name
|
|
||||||
|
|
||||||
datablock_ref = None
|
|
||||||
|
|
||||||
if item_id == 'Master Collection':
|
|
||||||
datablock_ref = bpy.context.scene
|
|
||||||
elif item_type in helpers.BPY_TYPES.keys():
|
|
||||||
datablock_ref = getattr(
|
|
||||||
bpy.data, helpers.BPY_TYPES[update.id.__class__.__name__])[update.id.name]
|
|
||||||
else:
|
|
||||||
if item_id in bpy.data.lights.keys():
|
|
||||||
datablock_ref = bpy.data.lights[item_id]
|
|
||||||
|
|
||||||
return datablock_ref
|
|
||||||
|
|
||||||
|
|
||||||
def toogle_update_dirty(context, update):
|
|
||||||
data_ref = get_datablock_from_update(update, context)
|
|
||||||
|
|
||||||
if data_ref:
|
|
||||||
data_ref.is_dirty = True
|
|
||||||
|
|
||||||
|
|
||||||
@persistent
|
|
||||||
def depsgraph_update(scene):
|
|
||||||
ctx = bpy.context
|
|
||||||
|
|
||||||
if client.instance and client.instance.state() == 3:
|
|
||||||
if ctx.mode in ['OBJECT', 'PAINT_GPENCIL']:
|
|
||||||
updates = ctx.view_layer.depsgraph.updates
|
|
||||||
username = ctx.window_manager.session.username
|
|
||||||
|
|
||||||
selected_objects = helpers.get_selected_objects(scene)
|
|
||||||
|
|
||||||
for update in reversed(updates):
|
|
||||||
if is_replicated(update):
|
|
||||||
if update.id.id == username or update.id.id == 'Common':
|
|
||||||
toogle_update_dirty(ctx, update)
|
|
||||||
else:
|
|
||||||
item = get_datablock_from_update(update, ctx)
|
|
||||||
|
|
||||||
# get parent authority
|
|
||||||
if hasattr(item, "id"):
|
|
||||||
parent_id = ctx.collection.id if ctx.collection.id != 'None' else ctx.scene.id
|
|
||||||
|
|
||||||
if parent_id == username or parent_id == 'Common':
|
|
||||||
item.id = username
|
|
||||||
|
|
||||||
item_type = item.__class__.__name__
|
|
||||||
|
|
||||||
if 'Light'in item.__class__.__name__:
|
|
||||||
item_type = 'Light'
|
|
||||||
|
|
||||||
key = "{}/{}".format(item_type, item.name)
|
|
||||||
client.instance.set(key)
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
getattr(bpy.data, helpers.BPY_TYPES[update.id.__class__.__name__]).remove(
|
|
||||||
item)
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
break
|
|
||||||
|
|
||||||
update_client_selected_object(ctx)
|
|
||||||
|
|
||||||
|
|
||||||
def register():
|
def register():
|
||||||
from bpy.utils import register_class
|
from bpy.utils import register_class
|
||||||
for cls in classes:
|
for cls in classes:
|
||||||
register_class(cls)
|
register_class(cls)
|
||||||
|
|
||||||
bpy.app.handlers.depsgraph_update_post.append(depsgraph_update)
|
presence.register()
|
||||||
draw.register()
|
|
||||||
|
|
||||||
|
|
||||||
def unregister():
|
def unregister():
|
||||||
global server
|
global client
|
||||||
|
|
||||||
draw.unregister()
|
presence.unregister()
|
||||||
|
|
||||||
if bpy.app.handlers.depsgraph_update_post.count(depsgraph_update) > 0:
|
if client and client.state == 2:
|
||||||
bpy.app.handlers.depsgraph_update_post.remove(depsgraph_update)
|
client.disconnect()
|
||||||
|
client = None
|
||||||
if server:
|
|
||||||
server.kill()
|
|
||||||
server = None
|
|
||||||
del server
|
|
||||||
|
|
||||||
if client.instance:
|
|
||||||
client.instance.exit()
|
|
||||||
client.instance = None
|
|
||||||
|
|
||||||
from bpy.utils import unregister_class
|
from bpy.utils import unregister_class
|
||||||
for cls in reversed(classes):
|
for cls in reversed(classes):
|
||||||
|
@ -3,12 +3,19 @@ import bgl
|
|||||||
import blf
|
import blf
|
||||||
import gpu
|
import gpu
|
||||||
import mathutils
|
import mathutils
|
||||||
|
import copy
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
|
||||||
from bpy_extras import view3d_utils
|
from bpy_extras import view3d_utils
|
||||||
from gpu_extras.batch import batch_for_shader
|
from gpu_extras.batch import batch_for_shader
|
||||||
|
|
||||||
global renderer
|
# from .libs import debug
|
||||||
|
# from .bl_types.bl_user import BlUser
|
||||||
|
# from .delayable import Draw
|
||||||
|
|
||||||
|
global renderer
|
||||||
|
|
||||||
def view3d_find():
|
def view3d_find():
|
||||||
for area in bpy.data.window_managers[0].windows[0].screen.areas:
|
for area in bpy.data.window_managers[0].windows[0].screen.areas:
|
||||||
@ -44,7 +51,7 @@ def get_target_far(region, rv3d, coord, distance):
|
|||||||
return [target.x, target.y, target.z]
|
return [target.x, target.y, target.z]
|
||||||
|
|
||||||
|
|
||||||
def get_client_view_rect():
|
def get_client_cam_points():
|
||||||
area, region, rv3d = view3d_find()
|
area, region, rv3d = view3d_find()
|
||||||
|
|
||||||
v1 = [0, 0, 0]
|
v1 = [0, 0, 0]
|
||||||
@ -64,12 +71,10 @@ def get_client_view_rect():
|
|||||||
v4 = get_target(region, rv3d, (width, 0))
|
v4 = get_target(region, rv3d, (width, 0))
|
||||||
|
|
||||||
v5 = get_target(region, rv3d, (width/2, height/2))
|
v5 = get_target(region, rv3d, (width/2, height/2))
|
||||||
v6 = get_target_far(region, rv3d, (width/2, height/2), 10)
|
v6 = list(rv3d.view_location)
|
||||||
|
v7 = get_target_far(region, rv3d, (width/2, height/2), -.8)
|
||||||
|
|
||||||
coords = [v1, v2, v3, v4,v5,v6]
|
coords = [v1,v2,v3,v4,v5,v6,v7]
|
||||||
indices = (
|
|
||||||
(1, 3), (2, 1), (3, 0), (2, 0)
|
|
||||||
)
|
|
||||||
|
|
||||||
return coords
|
return coords
|
||||||
|
|
||||||
@ -81,6 +86,44 @@ def get_client_2d(coords):
|
|||||||
else:
|
else:
|
||||||
return (0, 0)
|
return (0, 0)
|
||||||
|
|
||||||
|
class User():
|
||||||
|
def __init__(self, username=None, color=(0,0,0,1)):
|
||||||
|
self.name = username
|
||||||
|
self.color = color
|
||||||
|
self.location = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
|
||||||
|
self.active_object = ""
|
||||||
|
|
||||||
|
def update_location(self):
|
||||||
|
current_coords = get_client_cam_points()
|
||||||
|
area, region, rv3d = view3d_find()
|
||||||
|
|
||||||
|
current_coords = get_client_cam_points()
|
||||||
|
if current_coords:
|
||||||
|
self.location = list(current_coords)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def update_client_selected_object(self,context):
|
||||||
|
session = bpy.context.window_manager.session
|
||||||
|
username = bpy.context.window_manager.session.username
|
||||||
|
# client_data = client.get(client_key)
|
||||||
|
|
||||||
|
selected_objects = utils.get_selected_objects(context.scene)
|
||||||
|
if len(selected_objects) > 0 and len(client_data) > 0:
|
||||||
|
|
||||||
|
for obj in selected_objects:
|
||||||
|
# if obj not in client_data[0][1]['active_objects']:
|
||||||
|
client_data[0][1]['active_objects'] = selected_objects
|
||||||
|
|
||||||
|
client.set(client_key, client_data[0][1])
|
||||||
|
break
|
||||||
|
|
||||||
|
elif client_data and client_data[0][1]['active_objects']:
|
||||||
|
client_data[0][1]['active_objects'] = []
|
||||||
|
client.set(client_key, client_data[0][1])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class DrawFactory(object):
|
class DrawFactory(object):
|
||||||
|
|
||||||
@ -164,32 +207,31 @@ class DrawFactory(object):
|
|||||||
else:
|
else:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def draw_client(self, client):
|
def draw_client_camera(self,client_uuid, client_location, client_color):
|
||||||
if client:
|
if client_location:
|
||||||
name = client['id']
|
|
||||||
local_username = bpy.context.window_manager.session.username
|
local_username = bpy.context.window_manager.session.username
|
||||||
|
|
||||||
if name != local_username:
|
|
||||||
try:
|
try:
|
||||||
indices = (
|
indices = (
|
||||||
(1, 3), (2, 1), (3, 0), (2, 0),(4, 5)
|
(1, 3), (2, 1), (3, 0), (2, 0),(4,5),(1, 6), (2, 6), (3, 6), (0, 6)
|
||||||
)
|
)
|
||||||
|
|
||||||
shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')
|
shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')
|
||||||
position = client['location']
|
position = [tuple(coord) for coord in client_location]
|
||||||
color = client['color']
|
color = client_color
|
||||||
|
|
||||||
|
|
||||||
batch = batch_for_shader(
|
batch = batch_for_shader(
|
||||||
shader, 'LINES', {"pos": position}, indices=indices)
|
shader, 'LINES', {"pos": position}, indices=indices)
|
||||||
|
|
||||||
self.d3d_items[name] = (shader, batch, color)
|
self.d3d_items[client_uuid] = (shader, batch, color)
|
||||||
self.d2d_items[name] = (position[1], name, color)
|
self.d2d_items[client_uuid] = (position[1], client_uuid, color)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Draw client exception {}".format(e))
|
print("Draw client exception {}".format(e))
|
||||||
|
|
||||||
def draw3d_callback(self):
|
def draw3d_callback(self):
|
||||||
bgl.glLineWidth(2)
|
bgl.glLineWidth(1.5)
|
||||||
try:
|
try:
|
||||||
for shader, batch, color in self.d3d_items.values():
|
for shader, batch, color in self.d3d_items.values():
|
||||||
shader.bind()
|
shader.bind()
|
||||||
@ -205,7 +247,7 @@ class DrawFactory(object):
|
|||||||
|
|
||||||
if coords:
|
if coords:
|
||||||
blf.position(0, coords[0], coords[1]+10, 0)
|
blf.position(0, coords[0], coords[1]+10, 0)
|
||||||
blf.size(0, 10, 72)
|
blf.size(0, 16, 72)
|
||||||
blf.color(0, color[0], color[1], color[2], color[3])
|
blf.color(0, color[0], color[1], color[2], color[3])
|
||||||
blf.draw(0, font)
|
blf.draw(0, font)
|
||||||
|
|
118
server.py
118
server.py
@ -1,118 +0,0 @@
|
|||||||
import logging
|
|
||||||
import time
|
|
||||||
import environment
|
|
||||||
from operator import itemgetter
|
|
||||||
|
|
||||||
|
|
||||||
import zmq
|
|
||||||
import message
|
|
||||||
|
|
||||||
logger = logging.getLogger("Server")
|
|
||||||
logger.setLevel(logging.ERROR)
|
|
||||||
|
|
||||||
SUPPORTED_TYPES = [
|
|
||||||
'Client',
|
|
||||||
'Image',
|
|
||||||
'Texture',
|
|
||||||
'Curve',
|
|
||||||
'Material',
|
|
||||||
'Light',
|
|
||||||
'SunLight',
|
|
||||||
'SpotLight',
|
|
||||||
'AreaLight',
|
|
||||||
'PointLight',
|
|
||||||
'Camera',
|
|
||||||
'Mesh',
|
|
||||||
'Armature',
|
|
||||||
'GreasePencil',
|
|
||||||
'Object',
|
|
||||||
'Action',
|
|
||||||
'Collection',
|
|
||||||
'Scene',
|
|
||||||
]
|
|
||||||
|
|
||||||
class ServerAgent():
|
|
||||||
def __init__(self, context=zmq.Context.instance(), id="admin"):
|
|
||||||
self.context = context
|
|
||||||
self.config = environment.load_config()
|
|
||||||
self.port = int(self.config['port']) if "port" in self.config.keys() else 5555
|
|
||||||
self.pub_sock = None
|
|
||||||
self.request_sock = None
|
|
||||||
self.collector_sock = None
|
|
||||||
self.poller = None
|
|
||||||
|
|
||||||
self.property_map = {}
|
|
||||||
self.id = id
|
|
||||||
self.bind_ports()
|
|
||||||
# Main client loop registration
|
|
||||||
self.tick()
|
|
||||||
|
|
||||||
logger.info("{} client initialized".format(id))
|
|
||||||
|
|
||||||
def bind_ports(self):
|
|
||||||
# Update all clients
|
|
||||||
self.pub_sock = self.context.socket(zmq.PUB)
|
|
||||||
self.pub_sock.setsockopt(zmq.SNDHWM, 60)
|
|
||||||
self.pub_sock.bind("tcp://*:"+str(self.port+1))
|
|
||||||
time.sleep(0.2)
|
|
||||||
|
|
||||||
# Update request
|
|
||||||
self.request_sock = self.context.socket(zmq.ROUTER)
|
|
||||||
self.request_sock.setsockopt(zmq.IDENTITY, b'SERVER')
|
|
||||||
self.request_sock.setsockopt(zmq.RCVHWM, 60)
|
|
||||||
self.request_sock.bind("tcp://*:"+str(self.port))
|
|
||||||
|
|
||||||
# Update collector
|
|
||||||
self.collector_sock = self.context.socket(zmq.PULL)
|
|
||||||
self.collector_sock.setsockopt(zmq.RCVHWM, 60)
|
|
||||||
self.collector_sock.bind("tcp://*:"+str(self.port+2))
|
|
||||||
|
|
||||||
# poller for socket aggregation
|
|
||||||
self.poller = zmq.Poller()
|
|
||||||
self.poller.register(self.request_sock, zmq.POLLIN)
|
|
||||||
self.poller.register(self.collector_sock, zmq.POLLIN)
|
|
||||||
|
|
||||||
def tick(self):
|
|
||||||
logger.info("{} server launched on {}".format(id,self.port))
|
|
||||||
|
|
||||||
while True:
|
|
||||||
# Non blocking poller
|
|
||||||
socks = dict(self.poller.poll(1000))
|
|
||||||
|
|
||||||
# Snapshot system for late join (Server - Client)
|
|
||||||
if self.request_sock in socks:
|
|
||||||
msg = self.request_sock.recv_multipart(zmq.DONTWAIT)
|
|
||||||
|
|
||||||
identity = msg[0]
|
|
||||||
request = msg[1]
|
|
||||||
|
|
||||||
if request == b"SNAPSHOT_REQUEST":
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
logger.info("Bad snapshot request")
|
|
||||||
break
|
|
||||||
|
|
||||||
ordered_props = [(SUPPORTED_TYPES.index(k.split('/')[0]),k,v) for k, v in self.property_map.items()]
|
|
||||||
ordered_props.sort(key=itemgetter(0))
|
|
||||||
|
|
||||||
for i, k, v in ordered_props:
|
|
||||||
logger.info(
|
|
||||||
"Sending {} snapshot to {}".format(k, identity))
|
|
||||||
self.request_sock.send(identity, zmq.SNDMORE)
|
|
||||||
v.send(self.request_sock)
|
|
||||||
|
|
||||||
msg_end_snapshot = message.Message(key="SNAPSHOT_END", id=identity)
|
|
||||||
self.request_sock.send(identity, zmq.SNDMORE)
|
|
||||||
msg_end_snapshot.send(self.request_sock)
|
|
||||||
logger.info("done")
|
|
||||||
|
|
||||||
# Regular update routing (Clients / Client)
|
|
||||||
elif self.collector_sock in socks:
|
|
||||||
msg = message.Message.recv(self.collector_sock)
|
|
||||||
# logger.info("received object")
|
|
||||||
# Update all clients
|
|
||||||
msg.store(self.property_map)
|
|
||||||
msg.send(self.pub_sock)
|
|
||||||
|
|
||||||
server = ServerAgent()
|
|
||||||
|
|
301
ui.py
301
ui.py
@ -1,12 +1,18 @@
|
|||||||
import bpy
|
import bpy
|
||||||
from . import client
|
|
||||||
from . import operators
|
from . import operators
|
||||||
|
from .libs.replication.constants import *
|
||||||
|
from .bl_types.bl_user import BlUser
|
||||||
|
|
||||||
|
|
||||||
ICONS = {'Image': 'IMAGE_DATA', 'Curve':'CURVE_DATA', 'Client':'SOLO_ON','Collection': 'FILE_FOLDER', 'Mesh': 'MESH_DATA', 'Object': 'OBJECT_DATA', 'Material': 'MATERIAL_DATA',
|
ICONS = {'Image': 'IMAGE_DATA', 'Curve':'CURVE_DATA', 'Client':'SOLO_ON','Collection': 'FILE_FOLDER', 'Mesh': 'MESH_DATA', 'Object': 'OBJECT_DATA', 'Material': 'MATERIAL_DATA',
|
||||||
'Texture': 'TEXTURE_DATA', 'Scene': 'SCENE_DATA','AreaLight':'LIGHT_DATA', 'Light': 'LIGHT_DATA', 'SpotLight': 'LIGHT_DATA', 'SunLight': 'LIGHT_DATA', 'PointLight': 'LIGHT_DATA', 'Camera': 'CAMERA_DATA', 'Action': 'ACTION', 'Armature': 'ARMATURE_DATA', 'GreasePencil': 'GREASEPENCIL'}
|
'Texture': 'TEXTURE_DATA', 'Scene': 'SCENE_DATA','AreaLight':'LIGHT_DATA', 'Light': 'LIGHT_DATA', 'SpotLight': 'LIGHT_DATA', 'SunLight': 'LIGHT_DATA', 'PointLight': 'LIGHT_DATA', 'Camera': 'CAMERA_DATA', 'Action': 'ACTION', 'Armature': 'ARMATURE_DATA', 'GreasePencil': 'GREASEPENCIL'}
|
||||||
|
|
||||||
|
PROP_STATES = [ 'ADDED',
|
||||||
|
'COMMITED',
|
||||||
|
'PUSHED',
|
||||||
|
'FETCHED',
|
||||||
|
'UP',
|
||||||
|
'CHANGED']
|
||||||
class SESSION_PT_settings(bpy.types.Panel):
|
class SESSION_PT_settings(bpy.types.Panel):
|
||||||
"""Settings panel"""
|
"""Settings panel"""
|
||||||
bl_idname = "MULTIUSER_SETTINGS_PT_panel"
|
bl_idname = "MULTIUSER_SETTINGS_PT_panel"
|
||||||
@ -21,150 +27,161 @@ class SESSION_PT_settings(bpy.types.Panel):
|
|||||||
|
|
||||||
def draw(self, context):
|
def draw(self, context):
|
||||||
layout = self.layout
|
layout = self.layout
|
||||||
|
row = layout.row()
|
||||||
if hasattr(context.window_manager, 'session'):
|
if hasattr(context.window_manager, 'session'):
|
||||||
net_settings = context.window_manager.session
|
settings = context.window_manager.session
|
||||||
window_manager = context.window_manager
|
window_manager = context.window_manager
|
||||||
|
|
||||||
row = layout.row()
|
# STATE INITIAL
|
||||||
if not client.instance or (client.instance and client.instance.state() == 1):
|
if not operators.client or (operators.client and operators.client.state == 0):
|
||||||
row = layout.row()
|
pass
|
||||||
|
|
||||||
# USER SETTINGS
|
|
||||||
box = row.box()
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="USER", icon='TRIA_RIGHT')
|
|
||||||
row = box.row()
|
|
||||||
row.prop(window_manager.session, "username", text="id")
|
|
||||||
|
|
||||||
row = box.row()
|
|
||||||
row.prop(window_manager.session, "client_color", text="color")
|
|
||||||
row = box.row()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# NETWORK SETTINGS
|
|
||||||
row = layout.row()
|
|
||||||
box = row.box()
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="NETWORK", icon = "TRIA_RIGHT")
|
|
||||||
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="draw overlay:")
|
|
||||||
row.prop(net_settings, "enable_presence", text="")
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="clear blend:")
|
|
||||||
row.prop(net_settings, "start_empty", text="")
|
|
||||||
row = box.row()
|
|
||||||
|
|
||||||
row = box.row()
|
|
||||||
row.prop(net_settings, "session_mode", expand=True)
|
|
||||||
row = box.row()
|
|
||||||
|
|
||||||
if window_manager.session.session_mode == 'HOST':
|
|
||||||
box = row.box()
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="init scene:")
|
|
||||||
row.prop(net_settings, "init_scene", text="")
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="reset rights:")
|
|
||||||
row.prop(net_settings, "reset_rights", text="")
|
|
||||||
row = box.row()
|
|
||||||
row.operator("session.create", text="HOST")
|
|
||||||
else:
|
|
||||||
box = row.box()
|
|
||||||
row = box.row()
|
|
||||||
row.prop(net_settings, "ip", text="ip")
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="port:")
|
|
||||||
row.prop(window_manager.session, "port", text="")
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="load data:")
|
|
||||||
row.prop(net_settings, "load_data", text="")
|
|
||||||
|
|
||||||
|
|
||||||
row = box.row()
|
|
||||||
row.operator("session.join", text="CONNECT")
|
|
||||||
|
|
||||||
# REPLICATION SETTINGS
|
# REPLICATION SETTINGS
|
||||||
row = layout.row()
|
# row = layout.row()
|
||||||
box = row.box()
|
# box = row.box()
|
||||||
row = box.row()
|
# row = box.row()
|
||||||
row.label(text="REPLICATION", icon='TRIA_RIGHT')
|
# row.label(text="REPLICATION", icon='TRIA_RIGHT')
|
||||||
row = box.row()
|
# row = box.row()
|
||||||
|
|
||||||
for item in window_manager.session.supported_datablock:
|
|
||||||
row.label(text=item.type_name,icon=ICONS[item.type_name])
|
|
||||||
row.prop(item, "is_replicated", text="")
|
|
||||||
row = box.row()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# for item in window_manager.session.supported_datablock:
|
||||||
|
# row.label(text=item.type_name,icon=ICONS[item.type_name])
|
||||||
|
# row.prop(item, "is_replicated", text="")
|
||||||
|
# row = box.row()
|
||||||
else:
|
else:
|
||||||
if client.instance.state() == 3:
|
# STATE ACTIVE
|
||||||
|
if operators.client.state == 2:
|
||||||
|
|
||||||
row = layout.row()
|
row = layout.row()
|
||||||
row.operator("session.stop", icon='QUIT', text="Exit")
|
row.operator("session.stop", icon='QUIT', text="Exit")
|
||||||
# row = layout.row(align=True)
|
|
||||||
# row.operator("session.dump", icon='QUIT', text="Dump")
|
|
||||||
# row.operator("session.dump", icon='QUIT', text="Load")
|
|
||||||
row = layout.row()
|
row = layout.row()
|
||||||
|
|
||||||
box = row.box()
|
# STATE SYNCING
|
||||||
row = box.row()
|
|
||||||
row.label(text="", icon='INFO')
|
|
||||||
row = box.row()
|
|
||||||
row.label(text="Sync tasks: {}".format(client.instance.active_tasks))
|
|
||||||
else:
|
else:
|
||||||
status = "connecting..."
|
status = "connecting..."
|
||||||
if net_settings.is_admin:
|
|
||||||
status = "init scene...({} tasks remaining)".format(client.instance.active_tasks)
|
|
||||||
row.label(text=status)
|
row.label(text=status)
|
||||||
row = layout.row()
|
row = layout.row()
|
||||||
row.operator("session.stop", icon='QUIT', text="CANCEL")
|
row.operator("session.stop", icon='QUIT', text="CANCEL")
|
||||||
|
|
||||||
|
|
||||||
|
class SESSION_PT_settings_network(bpy.types.Panel):
|
||||||
|
bl_idname = "MULTIUSER_SETTINGS_NETWORK_PT_panel"
|
||||||
|
bl_label = "Network"
|
||||||
|
bl_space_type = 'VIEW_3D'
|
||||||
|
bl_region_type = 'UI'
|
||||||
|
bl_category = "Multiuser"
|
||||||
|
bl_parent_id = 'MULTIUSER_SETTINGS_PT_panel'
|
||||||
|
@classmethod
|
||||||
|
def poll(cls, context):
|
||||||
|
return not operators.client or (operators.client and operators.client.state == 0)
|
||||||
|
|
||||||
|
def draw(self, context):
|
||||||
|
layout = self.layout
|
||||||
|
|
||||||
|
settings = context.window_manager.session
|
||||||
|
scene = context.window_manager
|
||||||
|
row = layout.row()
|
||||||
|
# USER SETTINGS
|
||||||
|
row.label(text="draw overlay:")
|
||||||
|
row.prop(settings, "enable_presence", text="")
|
||||||
|
row = layout.row()
|
||||||
|
row.label(text="clear blend:")
|
||||||
|
row.prop(settings, "start_empty", text="")
|
||||||
|
row = layout.row()
|
||||||
|
|
||||||
|
row = layout.row()
|
||||||
|
row.prop(settings, "session_mode", expand=True)
|
||||||
|
row = layout.row()
|
||||||
|
|
||||||
|
if settings.session_mode == 'HOST':
|
||||||
|
box = row.box()
|
||||||
|
row = box.row()
|
||||||
|
row.label(text="init scene:")
|
||||||
|
row.prop(settings, "init_scene", text="")
|
||||||
|
row = box.row()
|
||||||
|
row.operator("session.start", text="HOST").host = True
|
||||||
|
else:
|
||||||
|
box = row.box()
|
||||||
|
row = box.row()
|
||||||
|
row.prop(settings, "ip", text="ip")
|
||||||
|
row = box.row()
|
||||||
|
row.label(text="port:")
|
||||||
|
row.prop(settings, "port", text="")
|
||||||
|
row = box.row()
|
||||||
|
|
||||||
|
|
||||||
|
row = box.row()
|
||||||
|
row.operator("session.start", text="CONNECT").host = False
|
||||||
|
|
||||||
|
|
||||||
|
class SESSION_PT_settings_user(bpy.types.Panel):
|
||||||
|
bl_idname = "MULTIUSER_SETTINGS_USER_PT_panel"
|
||||||
|
bl_label = "User"
|
||||||
|
bl_space_type = 'VIEW_3D'
|
||||||
|
bl_region_type = 'UI'
|
||||||
|
bl_category = "Multiuser"
|
||||||
|
bl_parent_id = 'MULTIUSER_SETTINGS_PT_panel'
|
||||||
|
@classmethod
|
||||||
|
def poll(cls, context):
|
||||||
|
return not operators.client or (operators.client and operators.client.state == 0)
|
||||||
|
|
||||||
|
def draw(self, context):
|
||||||
|
layout = self.layout
|
||||||
|
|
||||||
|
settings = context.window_manager.session
|
||||||
|
scene = context.window_manager
|
||||||
|
row = layout.row()
|
||||||
|
# USER SETTINGS
|
||||||
|
row.prop(settings, "username", text="id")
|
||||||
|
|
||||||
|
row = layout.row()
|
||||||
|
row.prop(settings, "client_color", text="color")
|
||||||
row = layout.row()
|
row = layout.row()
|
||||||
|
|
||||||
|
|
||||||
class SESSION_PT_user(bpy.types.Panel):
|
class SESSION_PT_user(bpy.types.Panel):
|
||||||
bl_idname = "MULTIUSER_USER_PT_panel"
|
bl_idname = "MULTIUSER_USER_PT_panel"
|
||||||
bl_label = "Users online"
|
bl_label = "Users"
|
||||||
bl_space_type = 'VIEW_3D'
|
bl_space_type = 'VIEW_3D'
|
||||||
bl_region_type = 'UI'
|
bl_region_type = 'UI'
|
||||||
bl_category = "Multiuser"
|
bl_category = "Multiuser"
|
||||||
|
bl_parent_id = 'MULTIUSER_SETTINGS_PT_panel'
|
||||||
@classmethod
|
@classmethod
|
||||||
def poll(cls, context):
|
def poll(cls, context):
|
||||||
return client.instance and client.instance.state() == 3
|
return operators.client and operators.client.state == 2
|
||||||
|
|
||||||
|
|
||||||
def draw(self, context):
|
def draw(self, context):
|
||||||
layout = self.layout
|
layout = self.layout
|
||||||
|
|
||||||
net_settings = context.window_manager.session
|
settings = context.window_manager.session
|
||||||
scene = context.window_manager
|
scene = context.window_manager
|
||||||
# Create a simple row.
|
# Create a simple row.
|
||||||
row = layout.row()
|
col = layout.column(align=True)
|
||||||
client_keys = client.instance.list()
|
|
||||||
|
client_keys = operators.client.list(filter=BlUser)
|
||||||
if client_keys and len(client_keys) > 0:
|
if client_keys and len(client_keys) > 0:
|
||||||
for key in client_keys:
|
for key in client_keys:
|
||||||
if 'Client' in key[0]:
|
area_msg = col.row(align = True)
|
||||||
|
item_box = area_msg.box()
|
||||||
|
client = operators.client.get(key).buffer
|
||||||
|
pointer = operators.client.get(key).pointer
|
||||||
info = ""
|
info = ""
|
||||||
item_box = row.box()
|
|
||||||
detail_item_box = item_box.row()
|
|
||||||
|
|
||||||
username = key[0].split('/')[1]
|
detail_item_row = item_box.row(align = True)
|
||||||
if username == net_settings.username:
|
|
||||||
|
username = client['name']
|
||||||
|
|
||||||
|
|
||||||
|
is_local_user = username == settings.username
|
||||||
|
|
||||||
|
if is_local_user:
|
||||||
info = "(self)"
|
info = "(self)"
|
||||||
# detail_item_box = item_box.row()
|
|
||||||
detail_item_box.label(
|
|
||||||
text="{} - {}".format(username, info))
|
|
||||||
|
|
||||||
if net_settings.username not in key[0]:
|
detail_item_row.label(
|
||||||
detail_item_box.operator(
|
text="{} {}".format(username, info))
|
||||||
"session.snapview", text="", icon='VIEW_CAMERA').target_client = username
|
|
||||||
|
if not is_local_user:
|
||||||
|
detail_item_row.operator(
|
||||||
|
"session.snapview", text="", icon='VIEW_CAMERA').target_client = key
|
||||||
row = layout.row()
|
row = layout.row()
|
||||||
else:
|
else:
|
||||||
row.label(text="Empty")
|
row.label(text="Empty")
|
||||||
@ -172,20 +189,16 @@ class SESSION_PT_user(bpy.types.Panel):
|
|||||||
row = layout.row()
|
row = layout.row()
|
||||||
|
|
||||||
|
|
||||||
def get_client_key(item):
|
class SESSION_PT_outliner(bpy.types.Panel):
|
||||||
return item[0]
|
|
||||||
|
|
||||||
|
|
||||||
class SESSION_PT_properties(bpy.types.Panel):
|
|
||||||
bl_idname = "MULTIUSER_PROPERTIES_PT_panel"
|
bl_idname = "MULTIUSER_PROPERTIES_PT_panel"
|
||||||
bl_label = "Replicated properties"
|
bl_label = "Properties"
|
||||||
bl_space_type = 'VIEW_3D'
|
bl_space_type = 'VIEW_3D'
|
||||||
bl_region_type = 'UI'
|
bl_region_type = 'UI'
|
||||||
bl_category = "Multiuser"
|
bl_category = "Multiuser"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def poll(cls, context):
|
def poll(cls, context):
|
||||||
return client.instance and client.instance.state() == 3
|
return operators.client and operators.client.state == 2
|
||||||
|
|
||||||
def draw_header(self, context):
|
def draw_header(self, context):
|
||||||
self.layout.label(text="", icon='OUTLINER_OB_GROUP_INSTANCE')
|
self.layout.label(text="", icon='OUTLINER_OB_GROUP_INSTANCE')
|
||||||
@ -194,57 +207,67 @@ class SESSION_PT_properties(bpy.types.Panel):
|
|||||||
layout = self.layout
|
layout = self.layout
|
||||||
|
|
||||||
if hasattr(context.window_manager,'session'):
|
if hasattr(context.window_manager,'session'):
|
||||||
net_settings = context.window_manager.session
|
settings = context.window_manager.session
|
||||||
scene = context.window_manager
|
scene = context.window_manager
|
||||||
|
|
||||||
row = layout.row()
|
row = layout.row()
|
||||||
|
row.prop(settings,'outliner_filter', text="")
|
||||||
|
|
||||||
row = layout.row(align=True)
|
row = layout.row(align=True)
|
||||||
row.prop(net_settings, "buffer", text="")
|
|
||||||
row.prop(net_settings, "add_property_depth", text="")
|
|
||||||
add = row.operator("session.add_prop", text="",
|
|
||||||
icon="ADD")
|
|
||||||
add.property_path = net_settings.buffer
|
|
||||||
add.depth = net_settings.add_property_depth
|
|
||||||
row = layout.row()
|
|
||||||
|
|
||||||
# Property area
|
# Property area
|
||||||
area_msg = row.box()
|
# area_msg = row.box()
|
||||||
client_keys = client.instance.list()
|
client_keys = operators.client.list()
|
||||||
|
|
||||||
if client_keys and len(client_keys) > 0:
|
if client_keys and len(client_keys) > 0:
|
||||||
for item in sorted(client_keys, key=get_client_key):
|
col = layout.column(align=True)
|
||||||
owner = 'toto'
|
for key in client_keys:
|
||||||
try:
|
item = operators.client.get(key)
|
||||||
owner = item[1]
|
|
||||||
except:
|
|
||||||
owner = item[1].decode()
|
|
||||||
pass
|
|
||||||
|
|
||||||
store_type,store_name = item[0].split('/')
|
if item.str_type == 'BlUser':
|
||||||
|
continue
|
||||||
|
|
||||||
|
area_msg = col.row(align = True)
|
||||||
item_box = area_msg.box()
|
item_box = area_msg.box()
|
||||||
|
name = "None"
|
||||||
|
#TODO: refactor that...
|
||||||
|
if hasattr(item.pointer,'name'):
|
||||||
|
name = item.pointer.name
|
||||||
|
else:
|
||||||
|
name = item.buffer['name']
|
||||||
|
|
||||||
detail_item_box = item_box.row(align = True)
|
detail_item_box = item_box.row()
|
||||||
detail_item_box.label(text="",icon=ICONS[store_type])
|
detail_item_box.label(text="",icon=item.icon)
|
||||||
detail_item_box.label(text="{} ".format(store_name))
|
detail_item_box.label(text="{} ".format(name))
|
||||||
detail_item_box.label(text="{} ".format(owner))
|
detail_item_box.label(text="{} ".format(item.owner))
|
||||||
|
|
||||||
|
if item.state == FETCHED:
|
||||||
|
detail_item_box.operator("session.apply", text=PROP_STATES[item.state]).target = item.uuid
|
||||||
|
else:
|
||||||
|
detail_item_box.label(text="{} ".format(PROP_STATES[item.state]))
|
||||||
|
|
||||||
|
detail_item_box.operator(
|
||||||
|
"session.remove_prop", text="", icon="X").property_path = key
|
||||||
|
|
||||||
right_icon = "DECORATE_UNLOCKED"
|
right_icon = "DECORATE_UNLOCKED"
|
||||||
if owner == net_settings.username or owner == "Common" :
|
if item.owner == settings.username:
|
||||||
right_icon="DECORATE_UNLOCKED"
|
right_icon="DECORATE_UNLOCKED"
|
||||||
else:
|
else:
|
||||||
|
|
||||||
right_icon="DECORATE_LOCKED"
|
right_icon="DECORATE_LOCKED"
|
||||||
|
|
||||||
ro = detail_item_box.operator("session.right", text="",emboss=net_settings.is_admin, icon=right_icon)
|
ro = detail_item_box.operator("session.right", text="", icon=right_icon)
|
||||||
ro.key = item[0]
|
ro.key = key
|
||||||
|
|
||||||
else:
|
else:
|
||||||
area_msg.label(text="Empty")
|
area_msg.label(text="Empty")
|
||||||
|
|
||||||
|
|
||||||
classes = (
|
classes = (
|
||||||
SESSION_PT_settings,
|
SESSION_PT_settings,
|
||||||
|
SESSION_PT_settings_user,
|
||||||
|
SESSION_PT_settings_network,
|
||||||
SESSION_PT_user,
|
SESSION_PT_user,
|
||||||
SESSION_PT_properties,
|
SESSION_PT_outliner,
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
213
utils.py
Normal file
213
utils.py
Normal file
@ -0,0 +1,213 @@
|
|||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from uuid import uuid4
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import string
|
||||||
|
import random
|
||||||
|
|
||||||
|
import bpy
|
||||||
|
import mathutils
|
||||||
|
|
||||||
|
from . import presence, environment
|
||||||
|
from .libs import dump_anything
|
||||||
|
|
||||||
|
# TODO: replace hardcoded values...
|
||||||
|
BPY_TYPES = {'Image': 'images', 'Texture': 'textures', 'Material': 'materials', 'GreasePencil': 'grease_pencils', 'Curve': 'curves', 'Collection': 'collections', 'Mesh': 'meshes', 'Object': 'objects',
|
||||||
|
'Scene': 'scenes', 'Light': 'lights', 'SunLight': 'lights', 'SpotLight': 'lights', 'AreaLight': 'lights', 'PointLight': 'lights', 'Camera': 'cameras', 'Action': 'actions', 'Armature': 'armatures'}
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
logger.setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
# UTILITY FUNCTIONS
|
||||||
|
def random_string_digits(stringLength=6):
|
||||||
|
"""Generate a random string of letters and digits """
|
||||||
|
lettersAndDigits = string.ascii_letters + string.digits
|
||||||
|
return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))
|
||||||
|
|
||||||
|
def clean_scene():
|
||||||
|
for datablock in BPY_TYPES:
|
||||||
|
datablock_ref = getattr(bpy.data, BPY_TYPES[datablock])
|
||||||
|
for item in datablock_ref:
|
||||||
|
try:
|
||||||
|
datablock_ref.remove(item)
|
||||||
|
# Catch last scene remove
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def revers(d):
|
||||||
|
l = []
|
||||||
|
for i in d:
|
||||||
|
l.append(i)
|
||||||
|
|
||||||
|
return l[::-1]
|
||||||
|
|
||||||
|
|
||||||
|
def get_armature_edition_context(armature):
|
||||||
|
|
||||||
|
override = {}
|
||||||
|
# Set correct area
|
||||||
|
for area in bpy.data.window_managers[0].windows[0].screen.areas:
|
||||||
|
if area.type == 'VIEW_3D':
|
||||||
|
override = bpy.context.copy()
|
||||||
|
override['area'] = area
|
||||||
|
break
|
||||||
|
|
||||||
|
# Set correct armature settings
|
||||||
|
override['window'] = bpy.data.window_managers[0].windows[0]
|
||||||
|
override['screen'] = bpy.data.window_managers[0].windows[0].screen
|
||||||
|
override['mode'] = 'EDIT_ARMATURE'
|
||||||
|
override['active_object'] = armature
|
||||||
|
override['selected_objects'] = [armature]
|
||||||
|
|
||||||
|
for o in bpy.data.objects:
|
||||||
|
if o.data == armature:
|
||||||
|
override['edit_object'] = o
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
return override
|
||||||
|
|
||||||
|
|
||||||
|
def get_selected_objects(scene):
|
||||||
|
selected_objects = []
|
||||||
|
for obj in scene.objects:
|
||||||
|
if obj.select_get():
|
||||||
|
selected_objects.append(obj.name)
|
||||||
|
|
||||||
|
return selected_objects
|
||||||
|
|
||||||
|
def load_dict(src_dict, target):
|
||||||
|
try:
|
||||||
|
for item in src_dict:
|
||||||
|
# attr =
|
||||||
|
setattr(target, item, src_dict[item])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(e)
|
||||||
|
pass
|
||||||
|
|
||||||
|
def resolve_bpy_path(path):
|
||||||
|
"""
|
||||||
|
Get bpy property value from path
|
||||||
|
"""
|
||||||
|
item = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
path = path.split('/')
|
||||||
|
item = getattr(bpy.data, BPY_TYPES[path[0]])[path[1]]
|
||||||
|
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def load_client(client=None, data=None):
|
||||||
|
C = bpy.context
|
||||||
|
D = bpy.data
|
||||||
|
net_settings = C.window_manager.session
|
||||||
|
|
||||||
|
if client and data:
|
||||||
|
if net_settings.enable_presence:
|
||||||
|
draw.renderer.draw_client(data)
|
||||||
|
draw.renderer.draw_client_selected_objects(data)
|
||||||
|
|
||||||
|
|
||||||
|
def load_armature(target=None, data=None, create=False):
|
||||||
|
file = "cache_{}.json".format(data['name'])
|
||||||
|
context = bpy.context
|
||||||
|
|
||||||
|
if not target:
|
||||||
|
target = bpy.data.armatures.new(data['name'])
|
||||||
|
|
||||||
|
dump_anything.load(target, data)
|
||||||
|
|
||||||
|
with open(file, 'w') as fp:
|
||||||
|
json.dump(data, fp)
|
||||||
|
fp.close()
|
||||||
|
|
||||||
|
target.id = data['id']
|
||||||
|
else:
|
||||||
|
# Construct a correct execution context
|
||||||
|
file = "cache_{}.json".format(target.name)
|
||||||
|
|
||||||
|
with open(file, 'r') as fp:
|
||||||
|
data = json.load(fp)
|
||||||
|
|
||||||
|
if data:
|
||||||
|
ob = None
|
||||||
|
for o in bpy.data.objects:
|
||||||
|
if o.data == target:
|
||||||
|
ob = o
|
||||||
|
if ob:
|
||||||
|
bpy.context.view_layer.objects.active = ob
|
||||||
|
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
|
||||||
|
for eb in data['edit_bones']:
|
||||||
|
if eb in target.edit_bones.keys():
|
||||||
|
# Update the bone
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
# Add new edit bone and load it
|
||||||
|
|
||||||
|
target_new_b = target.edit_bones.new[eb]
|
||||||
|
dump_anything.load(target_new_b, data['bones'][eb])
|
||||||
|
|
||||||
|
logger.debug(eb)
|
||||||
|
|
||||||
|
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
|
||||||
|
fp.close()
|
||||||
|
import os
|
||||||
|
os.remove(file)
|
||||||
|
|
||||||
|
def dump_datablock(datablock, depth):
|
||||||
|
if datablock:
|
||||||
|
dumper = dump_anything.Dumper()
|
||||||
|
dumper.type_subset = dumper.match_subset_all
|
||||||
|
dumper.depth = depth
|
||||||
|
|
||||||
|
datablock_type = datablock.bl_rna.name
|
||||||
|
key = "{}/{}".format(datablock_type, datablock.name)
|
||||||
|
data = dumper.dump(datablock)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def dump_datablock_attibutes(datablock=None, attributes=[], depth=1, dickt=None):
|
||||||
|
if datablock:
|
||||||
|
dumper = dump_anything.Dumper()
|
||||||
|
dumper.type_subset = dumper.match_subset_all
|
||||||
|
dumper.depth = depth
|
||||||
|
|
||||||
|
datablock_type = datablock.bl_rna.name
|
||||||
|
key = "{}/{}".format(datablock_type, datablock.name)
|
||||||
|
|
||||||
|
data = {}
|
||||||
|
|
||||||
|
if dickt:
|
||||||
|
data = dickt
|
||||||
|
for attr in attributes:
|
||||||
|
try:
|
||||||
|
data[attr] = dumper.dump(getattr(datablock, attr))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def init_client(key=None):
|
||||||
|
client_dict = {}
|
||||||
|
|
||||||
|
C = bpy.context
|
||||||
|
Net = C.window_manager.session
|
||||||
|
client_dict['uuid'] = str(uuid4())
|
||||||
|
client_dict['location'] = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
|
||||||
|
client_dict['color'] = [Net.client_color.r,
|
||||||
|
Net.client_color.g, Net.client_color.b, 1]
|
||||||
|
|
||||||
|
client_dict['active_objects'] = get_selected_objects(C.view_layer)
|
||||||
|
|
||||||
|
return client_dict
|
Reference in New Issue
Block a user