diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..951a73e4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +fake_bpy_modules* +__pycache__ +.DS_Store \ No newline at end of file diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 00000000..5bdb0eff --- /dev/null +++ b/.pylintrc @@ -0,0 +1,575 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape, + invalid-name, + missing-docstring, + assignment-from-no-return, + import-error, + protected-access + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, while `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package.. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled). +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement. +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..ea958dd3 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "python.autoComplete.extraPaths": [ + "../fake_bpy_modules_2.80-20190718" + ] +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..14e2f777 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 00000000..e512741f --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Blender Hubs Exporter + +This addon extends the glTF 2.0 exporter to support the `MOZ_hubs_components` extension allowing you to add behavior to glTF assets for [Mozilla Hubs](https://hubs.mozilla.com). \ No newline at end of file diff --git a/io_scene_hubs/__init__.py b/io_scene_hubs/__init__.py new file mode 100644 index 00000000..6191f405 --- /dev/null +++ b/io_scene_hubs/__init__.py @@ -0,0 +1,495 @@ +import os +import json +import datetime +import bpy +from bpy.props import IntVectorProperty, BoolProperty, FloatProperty, StringProperty +from bpy.props import PointerProperty, FloatVectorProperty, CollectionProperty, IntProperty +from bpy.types import PropertyGroup, Panel, Operator, Menu +from bpy.app.handlers import persistent +from io_scene_gltf2.blender.exp import gltf2_blender_gather, gltf2_blender_gather_nodes +from io_scene_gltf2.blender.exp.gltf2_blender_gltf2_exporter import GlTF2Exporter +from io_scene_gltf2.io.exp import gltf2_io_export +from io_scene_gltf2.io.com import gltf2_io_extensions +from io_scene_gltf2.blender.com import gltf2_blender_json + +bl_info = { + "name" : "io_scene_hubs", + "author" : "Robert Long", + "description" : "", + "blender" : (2, 80, 0), + "version" : (0, 0, 1), + "location" : "", + "warning" : "", + "category" : "Generic" +} + +# Get the path to the default config file +paths = bpy.utils.script_paths("addons") + +default_config_filename = 'default-config.json' +default_config_path = default_config_filename + +for path in paths: + default_config_path = os.path.join(path, "io_scene_hubs", default_config_filename) + if os.path.exists(default_config_path): + break + +bpy.hubs_config = None +bpy.registered_hubs_components = {} + +class HubsComponentName(PropertyGroup): + name: bpy.props.StringProperty(name="name") + +class HubsComponentList(PropertyGroup): + items: bpy.props.CollectionProperty(type=HubsComponentName) + +class HubsSettings(PropertyGroup): + def config_updated(self, _context): + self.reload_config() + + def reload_config(self): + self.load_config(self.config_path) + + def load_config(self, config_path): + if os.path.splitext(config_path)[1] == '.json': + with open(bpy.path.abspath(config_path)) as config_file: + bpy.hubs_config = json.load(config_file) + else: + print('Config must be a .json file!') + + try: + for component_name, component_class in bpy.registered_hubs_components.items(): + component_class_name = "hubs_component_%s" % component_name.replace('-', '_') + delattr(bpy.types.Object, component_class_name) + bpy.utils.unregister_class(component_class) + except UnboundLocalError: + pass + bpy.registered_hubs_components = {} + + for component_name, component_definition in bpy.hubs_config['components'].items(): + component_class_name = "hubs_component_%s" % component_name.replace('-', '_') + component_property_dict = {} + + for property_name, property_definition in component_definition['properties'].items(): + property_type = property_definition['type'] + + if property_type == 'int': + component_property_dict[property_name] = IntProperty( + name=property_name + ) + elif property_type == 'float': + component_property_dict[property_name] = FloatProperty( + name=property_name + ) + elif property_type == 'bool': + component_property_dict[property_name] = BoolProperty( + name=property_name + ) + elif property_type == 'string': + component_property_dict[property_name] = StringProperty( + name=property_name + ) + elif property_type == 'ivec2': + component_property_dict[property_name] = IntVectorProperty( + name=property_name, + size=2 + ) + elif property_type == 'ivec3': + component_property_dict[property_name] = IntVectorProperty( + name=property_name, + size=3 + ) + elif property_type == 'ivec4': + component_property_dict[property_name] = IntVectorProperty( + name=property_name, + size=4 + ) + elif property_type == 'vec2': + component_property_dict[property_name] = FloatVectorProperty( + name=property_name, + size=2 + ) + elif property_type == 'vec3': + component_property_dict[property_name] = FloatVectorProperty( + name=property_name, + size=3 + ) + elif property_type == 'vec4': + component_property_dict[property_name] = FloatVectorProperty( + name=property_name, + size=4 + ) + elif property_type == 'color': + component_property_dict[property_name] = FloatVectorProperty( + name=property_name, + subtype='COLOR', + default=(1.0, 1.0, 1.0, 1.0), + size=4, + min=0, + max=1 + ) + else: + raise TypeError('Unsupported Hubs property type \'%s\' for %s on %s' % ( + property_type, property_name, component_name)) + + component_class = type(component_class_name, (PropertyGroup,), component_property_dict) + bpy.utils.register_class(component_class) + setattr(bpy.types.Object, component_class_name, PointerProperty(type=component_class)) + bpy.registered_hubs_components[component_name] = component_class + + config_path: StringProperty( + name="config_path", + description="Path to the config file", + default=default_config_path, + options={'HIDDEN'}, + maxlen=1024, + subtype='FILE_PATH', + update=config_updated + ) + +class AddHubsComponentMenu(Menu): + bl_label = "Add Hubs Component" + bl_idname = "OBJECT_MT_add_hubs_component_menu" + + def draw(self, context): + layout = self.layout + + for component_name in bpy.registered_hubs_components: + layout.operator( + "wm.add_hubs_component", + text=component_name + ).component_name = component_name + +class HubsObjectPanel(Panel): + bl_label = "Hubs" + bl_idname = "OBJECT_PT_hubs" + bl_space_type = 'PROPERTIES' + bl_region_type = 'WINDOW' + bl_context = "object" + + def draw(self, context): + layout = self.layout + obj = context.object + + if bpy.hubs_config is None: + return + + for component_item in obj.hubs_component_list.items: + component_name = component_item.name + component_definition = bpy.hubs_config['components'][component_name] + component_class = bpy.registered_hubs_components[component_name] + component_class_name = component_class.__name__ + component = getattr(obj, component_class_name) + + row = layout.row() + row.label(text=component_name) + row.operator( + "wm.remove_hubs_component", + text="", + icon="X" + ).component_name = component_name + + split = layout.split(factor=0.1) + col = split.column() + col.label(text=" ") + col = split.column() + for property_name, _property_definition in component_definition['properties'].items(): + col.prop(data=component, property=property_name) + + layout.separator() + + layout.operator( + "wm.call_menu", + text="Add Component" + ).name = "OBJECT_MT_add_hubs_component_menu" + +class HubsSettingsPanel(Panel): + bl_label = 'Hubs' + bl_idname = "SCENE_PT_hubs" + bl_space_type = 'PROPERTIES' + bl_region_type = 'WINDOW' + bl_context = 'scene' + + def draw(self, context): + layout = self.layout + + row = layout.row() + row.prop(context.scene.hubs_settings, "config_path", text="Config File") + row.operator("wm.reload_hubs_config", text="", icon="FILE_REFRESH") + + row = layout.row() + row.operator("wm.export_hubs_gltf", text="Export Scene") + row.operator("wm.export_hubs_gltf", text="Export Selected").selected = True + +class AddHubsComponent(Operator): + bl_idname = "wm.add_hubs_component" + bl_label = "Add Hubs Component" + + component_name: StringProperty(name="component_name") + + def execute(self, context): + if self.component_name == '': + return + + obj = context.object + item = obj.hubs_component_list.items.add() + item.name = self.component_name + context.area.tag_redraw() + return {'FINISHED'} + +class RemoveHubsComponent(Operator): + bl_idname = "wm.remove_hubs_component" + bl_label = "Remove Hubs Component" + + component_name: StringProperty(name="component_name") + + def execute(self, context): + if self.component_name == '': + return + + obj = context.object + items = obj.hubs_component_list.items + items.remove(items.find(self.component_name)) + context.area.tag_redraw() + return {'FINISHED'} + +class ReloadHubsConfig(Operator): + bl_idname = "wm.reload_hubs_config" + bl_label = "Reload Hubs Config" + + def execute(self, context): + context.scene.hubs_settings.reload_config() + context.area.tag_redraw() + return {'FINISHED'} + +class ExportHubsGLTF(Operator): + bl_idname = "wm.export_hubs_gltf" + bl_label = "Export Hubs GLTF" + + selected: BoolProperty(name="selected", default=False) + + def __fix_json(self, obj): + # TODO: move to custom JSON encoder + fixed = obj + if isinstance(obj, dict): + fixed = {} + for key, value in obj.items(): + if not self.__should_include_json_value(key, value): + continue + fixed[key] = self.__fix_json(value) + elif isinstance(obj, list): + fixed = [] + for value in obj: + fixed.append(self.__fix_json(value)) + elif isinstance(obj, float): + # force floats to int, if they are integers + # (prevent INTEGER_WRITTEN_AS_FLOAT validator warnings) + if int(obj) == obj: + return int(obj) + return fixed + + def __should_include_json_value(self, key, value): + allowed_empty_collections = ["KHR_materials_unlit"] + + if value is None: + return False + elif self.__is_empty_collection(value) and key not in allowed_empty_collections: + return False + return True + + + def __is_empty_collection(self, value): + return (isinstance(value, dict) or isinstance(value, list)) and len(value) == 0 + + def execute(self, context): + if bpy.data.filepath == '': + self.report({'ERROR'}, 'Save project before exporting') + return {'CANCELLED'} + + filepath = bpy.data.filepath.replace('.blend', '') + filename_ext = '.glb' + + export_settings = {} + export_settings['timestamp'] = datetime.datetime.now() + export_settings['gltf_filepath'] = bpy.path.ensure_ext(filepath, filename_ext) + + if os.path.exists(export_settings['gltf_filepath']): + os.remove(export_settings['gltf_filepath']) + + export_settings['gltf_filedirectory'] = os.path.dirname( + export_settings['gltf_filepath']) + '/' + export_settings['gltf_format'] = 'GLB' + export_settings['gltf_image_format'] = 'NAME' + export_settings['gltf_copyright'] = '' + export_settings['gltf_texcoords'] = True + export_settings['gltf_normals'] = True + export_settings['gltf_tangents'] = False + export_settings['gltf_draco_mesh_compression'] = False + export_settings['gltf_materials'] = True + export_settings['gltf_colors'] = True + export_settings['gltf_cameras'] = False + export_settings['gltf_selected'] = self.selected + export_settings['gltf_layers'] = True + export_settings['gltf_extras'] = False + export_settings['gltf_yup'] = True + export_settings['gltf_apply'] = False + export_settings['gltf_current_frame'] = False + export_settings['gltf_animations'] = False + export_settings['gltf_frame_range'] = False + export_settings['gltf_move_keyframes'] = False + export_settings['gltf_force_sampling'] = False + export_settings['gltf_skins'] = False + export_settings['gltf_all_vertex_influences'] = False + export_settings['gltf_frame_step'] = 1 + export_settings['gltf_morph'] = False + export_settings['gltf_morph_normal'] = False + export_settings['gltf_morph_tangent'] = False + export_settings['gltf_lights'] = False + export_settings['gltf_displacement'] = False + export_settings['gltf_binary'] = bytearray() + export_settings['gltf_binaryfilename'] = os.path.splitext( + os.path.basename(bpy.path.ensure_ext(filepath, filename_ext)))[0] + '.bin' + + # TODO: In most recent version this function will return active_scene + # as the first value for a total of 3 return values + scenes, _animations = gltf2_blender_gather.gather_gltf2(export_settings) + + # Modify scene here + + exporter = GlTF2Exporter(export_settings['gltf_copyright']) + exporter.add_scene(scenes[0], True) + buffer = exporter.finalize_buffer(export_settings['gltf_filedirectory'], is_glb=True) + exporter.finalize_images(export_settings['gltf_filedirectory']) + + gltf_json = self.__fix_json(exporter.glTF.to_dict()) + + extension_name = bpy.hubs_config["gltfExtensionName"] + gltf_json['extensionsRequired'].remove(extension_name) + + if not gltf_json['extensionsRequired']: + del gltf_json['extensionsRequired'] + + if 'extensions' not in gltf_json: + gltf_json['extensions'] = {} + + gltf_json['extensions'][extension_name] = { + "version": bpy.hubs_config["gltfExtensionVersion"] + } + + gltf2_io_export.save_gltf( + gltf_json, + export_settings, + gltf2_blender_json.BlenderJSONEncoder, + buffer + ) + + self.report({'INFO'}, 'Project saved to \"%s\"' % (export_settings['gltf_filepath'])) + + return {'FINISHED'} + +original_gather_extensions = gltf2_blender_gather_nodes.__gather_extensions + +def __to_json_compatible(value): + """Make a value (usually a custom property) compatible with json""" + + if isinstance(value, bpy.types.ID): + return value + + elif isinstance(value, str): + return value + + elif isinstance(value, (int, float)): + return value + + # for list classes + elif isinstance(value, list): + value = list(value) + # make sure contents are json-compatible too + for index in range(len(value)): + value[index] = __to_json_compatible(value[index]) + return value + + # for IDPropertyArray classes + elif hasattr(value, "to_list"): + value = value.to_list() + return value + + elif hasattr(value, "to_dict"): + value = value.to_dict() + if gltf2_blender_json.is_json_convertible(value): + return value + + return None + +def patched_gather_extensions(blender_object, export_settings): + extensions = original_gather_extensions(blender_object, export_settings) + + component_list = blender_object.hubs_component_list + + if component_list.items: + extension_name = bpy.hubs_config["gltfExtensionName"] + component_data = {} + + for component_item in component_list.items: + component_name = component_item.name + component_data[component_name] = {} + component_definition = bpy.hubs_config['components'][component_name] + component_class = bpy.registered_hubs_components[component_name] + component_class_name = component_class.__name__ + component = getattr(blender_object, component_class_name) + + for property_name, _property_definition in component_definition['properties'].items(): + component_data[component_name][property_name] = __to_json_compatible( + getattr(component, property_name) + ) + + if extensions is None: + extensions = {} + + extensions[extension_name] = gltf2_io_extensions.Extension( + name=extension_name, + extension=component_data, + required=False + ) + + return extensions if extensions else None + +@persistent +def load_handler(_dummy): + bpy.context.scene.hubs_settings.reload_config() + +def register(): + bpy.utils.register_class(HubsSettings) + bpy.utils.register_class(HubsComponentName) + bpy.utils.register_class(HubsComponentList) + bpy.utils.register_class(AddHubsComponentMenu) + bpy.types.Scene.hubs_settings = PointerProperty(type=HubsSettings) + bpy.types.Object.hubs_component_list = PointerProperty(type=HubsComponentList) + bpy.utils.register_class(HubsSettingsPanel) + bpy.utils.register_class(HubsObjectPanel) + bpy.utils.register_class(ReloadHubsConfig) + bpy.utils.register_class(AddHubsComponent) + bpy.utils.register_class(RemoveHubsComponent) + bpy.utils.register_class(ExportHubsGLTF) + bpy.app.handlers.load_post.append(load_handler) + gltf2_blender_gather_nodes.__gather_extensions = patched_gather_extensions + +def unregister(): + bpy.utils.unregister_class(ReloadHubsConfig) + bpy.utils.unregister_class(HubsObjectPanel) + bpy.utils.unregister_class(HubsSettingsPanel) + bpy.utils.unregister_class(HubsSettings) + bpy.utils.unregister_class(AddHubsComponentMenu) + bpy.utils.unregister_class(HubsComponentName) + bpy.utils.unregister_class(HubsComponentList) + bpy.utils.unregister_class(AddHubsComponent) + bpy.utils.unregister_class(RemoveHubsComponent) + bpy.utils.unregister_class(ExportHubsGLTF) + del bpy.types.Scene.hubs_settings + del bpy.types.Object.hubs_component_list + bpy.hubs_config = None + bpy.registered_hubs_components = {} + gltf2_blender_gather_nodes.__gather_extensions = original_gather_extensions + +if __name__ == "__main__": + register() diff --git a/io_scene_hubs/default-config.json b/io_scene_hubs/default-config.json new file mode 100644 index 00000000..3b0a7921 --- /dev/null +++ b/io_scene_hubs/default-config.json @@ -0,0 +1,16 @@ +{ + "gltfExtensionName": "MOZ_hubs_components", + "gltfExtensionVersion": 3, + "components": { + "kit-piece": { + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + } + } + } + } +} \ No newline at end of file diff --git a/setup.sh b/setup.sh new file mode 100755 index 00000000..2e07ad77 --- /dev/null +++ b/setup.sh @@ -0,0 +1 @@ +wget https://github.com/nutti/fake-bpy-module/releases/download/20190718/fake_bpy_modules_2.80-20190718.zip -O temp.zip; unzip temp.zip; rm temp.zip \ No newline at end of file