nwo
stringlengths 6
76
| sha
stringlengths 40
40
| path
stringlengths 5
118
| language
stringclasses 1
value | identifier
stringlengths 1
89
| parameters
stringlengths 2
5.4k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
51.1k
| docstring
stringlengths 1
17.6k
| docstring_summary
stringlengths 0
7.02k
| docstring_tokens
sequence | function
stringlengths 30
51.1k
| function_tokens
sequence | url
stringlengths 85
218
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AonCyberLabs/EvilAbigail | 5bde1d49a76ef2e5a6e6bcda5b094441b41144ad | evilmaid.py | python | UI.preplog | (self) | Draw the logging window | Draw the logging window | [
"Draw",
"the",
"logging",
"window"
] | def preplog(self):
"""
Draw the logging window
"""
self.log = self.screen.subwin((self.height/2), (self.width-2)/2, self.height/2, 1)
self.log.erase()
self.log.border()
self.screen.addstr((self.height/2), 4, "Log") | [
"def",
"preplog",
"(",
"self",
")",
":",
"self",
".",
"log",
"=",
"self",
".",
"screen",
".",
"subwin",
"(",
"(",
"self",
".",
"height",
"/",
"2",
")",
",",
"(",
"self",
".",
"width",
"-",
"2",
")",
"/",
"2",
",",
"self",
".",
"height",
"/",
"2",
",",
"1",
")",
"self",
".",
"log",
".",
"erase",
"(",
")",
"self",
".",
"log",
".",
"border",
"(",
")",
"self",
".",
"screen",
".",
"addstr",
"(",
"(",
"self",
".",
"height",
"/",
"2",
")",
",",
"4",
",",
"\"Log\"",
")"
] | https://github.com/AonCyberLabs/EvilAbigail/blob/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/evilmaid.py#L199-L206 |
||
AonCyberLabs/EvilAbigail | 5bde1d49a76ef2e5a6e6bcda5b094441b41144ad | evilmaid.py | python | UI.logger | (self, line, status, continuing = False) | Log a line to the logging window. Autoscrolls
A progress of 1.0 will fill the current bar accordingly (useful for 'continue')
Auto splits and indents long lines | Log a line to the logging window. Autoscrolls
A progress of 1.0 will fill the current bar accordingly (useful for 'continue')
Auto splits and indents long lines | [
"Log",
"a",
"line",
"to",
"the",
"logging",
"window",
".",
"Autoscrolls",
"A",
"progress",
"of",
"1",
".",
"0",
"will",
"fill",
"the",
"current",
"bar",
"accordingly",
"(",
"useful",
"for",
"continue",
")",
"Auto",
"splits",
"and",
"indents",
"long",
"lines"
] | def logger(self, line, status, continuing = False):
"""
Log a line to the logging window. Autoscrolls
A progress of 1.0 will fill the current bar accordingly (useful for 'continue')
Auto splits and indents long lines
"""
statuses = {
"ERROR": curses.color_pair(1),
"INFO": curses.color_pair(2)
}
if status == "ERROR" and not continuing:
progress = 1.0
else:
progress = self.idx/self.items
self.idx += 1
first = True
while line:
if first:
first = False
self.loglines.append((line[:37], status))
line = line[37:]
else:
self.loglines.append((' '+line[:35], status))
line = line[35:]
self.preplog()
for idx, line in enumerate(self.loglines[-((self.height/2)-3):]):
self.log.addstr(idx+1, 1, line[0], statuses[line[1]])
if progress:
self.plot(progress)
self.refresh() | [
"def",
"logger",
"(",
"self",
",",
"line",
",",
"status",
",",
"continuing",
"=",
"False",
")",
":",
"statuses",
"=",
"{",
"\"ERROR\"",
":",
"curses",
".",
"color_pair",
"(",
"1",
")",
",",
"\"INFO\"",
":",
"curses",
".",
"color_pair",
"(",
"2",
")",
"}",
"if",
"status",
"==",
"\"ERROR\"",
"and",
"not",
"continuing",
":",
"progress",
"=",
"1.0",
"else",
":",
"progress",
"=",
"self",
".",
"idx",
"/",
"self",
".",
"items",
"self",
".",
"idx",
"+=",
"1",
"first",
"=",
"True",
"while",
"line",
":",
"if",
"first",
":",
"first",
"=",
"False",
"self",
".",
"loglines",
".",
"append",
"(",
"(",
"line",
"[",
":",
"37",
"]",
",",
"status",
")",
")",
"line",
"=",
"line",
"[",
"37",
":",
"]",
"else",
":",
"self",
".",
"loglines",
".",
"append",
"(",
"(",
"' '",
"+",
"line",
"[",
":",
"35",
"]",
",",
"status",
")",
")",
"line",
"=",
"line",
"[",
"35",
":",
"]",
"self",
".",
"preplog",
"(",
")",
"for",
"idx",
",",
"line",
"in",
"enumerate",
"(",
"self",
".",
"loglines",
"[",
"-",
"(",
"(",
"self",
".",
"height",
"/",
"2",
")",
"-",
"3",
")",
":",
"]",
")",
":",
"self",
".",
"log",
".",
"addstr",
"(",
"idx",
"+",
"1",
",",
"1",
",",
"line",
"[",
"0",
"]",
",",
"statuses",
"[",
"line",
"[",
"1",
"]",
"]",
")",
"if",
"progress",
":",
"self",
".",
"plot",
"(",
"progress",
")",
"self",
".",
"refresh",
"(",
")"
] | https://github.com/AonCyberLabs/EvilAbigail/blob/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/evilmaid.py#L208-L237 |
||
AonCyberLabs/EvilAbigail | 5bde1d49a76ef2e5a6e6bcda5b094441b41144ad | evilmaid.py | python | UI.nextdrive | (self, items) | Signifies the start of the next drive for the current progress bar
Items is how many logging evens we expect to see on the main path | Signifies the start of the next drive for the current progress bar
Items is how many logging evens we expect to see on the main path | [
"Signifies",
"the",
"start",
"of",
"the",
"next",
"drive",
"for",
"the",
"current",
"progress",
"bar",
"Items",
"is",
"how",
"many",
"logging",
"evens",
"we",
"expect",
"to",
"see",
"on",
"the",
"main",
"path"
] | def nextdrive(self, items):
"""
Signifies the start of the next drive for the current progress bar
Items is how many logging evens we expect to see on the main path
"""
self.idx = 1
self.items = float(items) | [
"def",
"nextdrive",
"(",
"self",
",",
"items",
")",
":",
"self",
".",
"idx",
"=",
"1",
"self",
".",
"items",
"=",
"float",
"(",
"items",
")"
] | https://github.com/AonCyberLabs/EvilAbigail/blob/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/evilmaid.py#L239-L245 |
||
AonCyberLabs/EvilAbigail | 5bde1d49a76ef2e5a6e6bcda5b094441b41144ad | evilmaid.py | python | UI.incritems | (self, items) | Allows adding to how many steps we expect to see
For branch based differences | Allows adding to how many steps we expect to see
For branch based differences | [
"Allows",
"adding",
"to",
"how",
"many",
"steps",
"we",
"expect",
"to",
"see",
"For",
"branch",
"based",
"differences"
] | def incritems(self, items):
"""
Allows adding to how many steps we expect to see
For branch based differences
"""
self.items += items | [
"def",
"incritems",
"(",
"self",
",",
"items",
")",
":",
"self",
".",
"items",
"+=",
"items"
] | https://github.com/AonCyberLabs/EvilAbigail/blob/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/evilmaid.py#L247-L252 |
||
AonCyberLabs/EvilAbigail | 5bde1d49a76ef2e5a6e6bcda5b094441b41144ad | evilmaid.py | python | UI.plot | (self, progress) | Actually fill the progress bars accordingly | Actually fill the progress bars accordingly | [
"Actually",
"fill",
"the",
"progress",
"bars",
"accordingly"
] | def plot(self, progress):
"""
Actually fill the progress bars accordingly
"""
if progress < self.prevprogress:
self.donedrives += 1
self.prevprogress = progress
progress = progress + self.donedrives
totalbar = int((progress/self.drives)*((self.width-2)/2))
currentbar = int(progress*((self.width-2)/2)) % (self.width/2)
self.preptotal()
self.prepcurrent()
self.totalbar.addstr(1, 1, "-"*(totalbar-2), curses.color_pair(2))
self.currentbar.addstr(1, 1, "-"*(currentbar-2), curses.color_pair(2))
self.refresh() | [
"def",
"plot",
"(",
"self",
",",
"progress",
")",
":",
"if",
"progress",
"<",
"self",
".",
"prevprogress",
":",
"self",
".",
"donedrives",
"+=",
"1",
"self",
".",
"prevprogress",
"=",
"progress",
"progress",
"=",
"progress",
"+",
"self",
".",
"donedrives",
"totalbar",
"=",
"int",
"(",
"(",
"progress",
"/",
"self",
".",
"drives",
")",
"*",
"(",
"(",
"self",
".",
"width",
"-",
"2",
")",
"/",
"2",
")",
")",
"currentbar",
"=",
"int",
"(",
"progress",
"*",
"(",
"(",
"self",
".",
"width",
"-",
"2",
")",
"/",
"2",
")",
")",
"%",
"(",
"self",
".",
"width",
"/",
"2",
")",
"self",
".",
"preptotal",
"(",
")",
"self",
".",
"prepcurrent",
"(",
")",
"self",
".",
"totalbar",
".",
"addstr",
"(",
"1",
",",
"1",
",",
"\"-\"",
"*",
"(",
"totalbar",
"-",
"2",
")",
",",
"curses",
".",
"color_pair",
"(",
"2",
")",
")",
"self",
".",
"currentbar",
".",
"addstr",
"(",
"1",
",",
"1",
",",
"\"-\"",
"*",
"(",
"currentbar",
"-",
"2",
")",
",",
"curses",
".",
"color_pair",
"(",
"2",
")",
")",
"self",
".",
"refresh",
"(",
")"
] | https://github.com/AonCyberLabs/EvilAbigail/blob/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/evilmaid.py#L254-L272 |
||
AonCyberLabs/EvilAbigail | 5bde1d49a76ef2e5a6e6bcda5b094441b41144ad | evilmaid.py | python | UI.refresh | (self) | Refresh the screen in order | Refresh the screen in order | [
"Refresh",
"the",
"screen",
"in",
"order"
] | def refresh(self):
"""
Refresh the screen in order
"""
self.totalbar.refresh()
self.currentbar.refresh()
self.log.refresh()
self.screen.refresh() | [
"def",
"refresh",
"(",
"self",
")",
":",
"self",
".",
"totalbar",
".",
"refresh",
"(",
")",
"self",
".",
"currentbar",
".",
"refresh",
"(",
")",
"self",
".",
"log",
".",
"refresh",
"(",
")",
"self",
".",
"screen",
".",
"refresh",
"(",
")"
] | https://github.com/AonCyberLabs/EvilAbigail/blob/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/evilmaid.py#L274-L281 |
||
AonCyberLabs/EvilAbigail | 5bde1d49a76ef2e5a6e6bcda5b094441b41144ad | evilmaid.py | python | UI.destroy | (self) | Clear screen and exit | Clear screen and exit | [
"Clear",
"screen",
"and",
"exit"
] | def destroy(self):
"""
Clear screen and exit
"""
self.screen.erase()
self.refresh()
curses.endwin() | [
"def",
"destroy",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"erase",
"(",
")",
"self",
".",
"refresh",
"(",
")",
"curses",
".",
"endwin",
"(",
")"
] | https://github.com/AonCyberLabs/EvilAbigail/blob/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/evilmaid.py#L283-L289 |
||
Ape/samsungctl | 81cf14aa138c32ff10aaa424864d6fc92b987322 | samsungctl/remote_websocket.py | python | RemoteWebsocket.close | (self) | Close the connection. | Close the connection. | [
"Close",
"the",
"connection",
"."
] | def close(self):
"""Close the connection."""
if self.connection:
self.connection.close()
self.connection = None
logging.debug("Connection closed.") | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
":",
"self",
".",
"connection",
".",
"close",
"(",
")",
"self",
".",
"connection",
"=",
"None",
"logging",
".",
"debug",
"(",
"\"Connection closed.\"",
")"
] | https://github.com/Ape/samsungctl/blob/81cf14aa138c32ff10aaa424864d6fc92b987322/samsungctl/remote_websocket.py#L38-L43 |
||
Ape/samsungctl | 81cf14aa138c32ff10aaa424864d6fc92b987322 | samsungctl/remote_websocket.py | python | RemoteWebsocket.control | (self, key) | Send a control command. | Send a control command. | [
"Send",
"a",
"control",
"command",
"."
] | def control(self, key):
"""Send a control command."""
if not self.connection:
raise exceptions.ConnectionClosed()
payload = json.dumps({
"method": "ms.remote.control",
"params": {
"Cmd": "Click",
"DataOfCmd": key,
"Option": "false",
"TypeOfRemote": "SendRemoteKey"
}
})
logging.info("Sending control command: %s", key)
self.connection.send(payload)
time.sleep(self._key_interval) | [
"def",
"control",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"connection",
":",
"raise",
"exceptions",
".",
"ConnectionClosed",
"(",
")",
"payload",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"method\"",
":",
"\"ms.remote.control\"",
",",
"\"params\"",
":",
"{",
"\"Cmd\"",
":",
"\"Click\"",
",",
"\"DataOfCmd\"",
":",
"key",
",",
"\"Option\"",
":",
"\"false\"",
",",
"\"TypeOfRemote\"",
":",
"\"SendRemoteKey\"",
"}",
"}",
")",
"logging",
".",
"info",
"(",
"\"Sending control command: %s\"",
",",
"key",
")",
"self",
".",
"connection",
".",
"send",
"(",
"payload",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_key_interval",
")"
] | https://github.com/Ape/samsungctl/blob/81cf14aa138c32ff10aaa424864d6fc92b987322/samsungctl/remote_websocket.py#L45-L62 |
||
Ape/samsungctl | 81cf14aa138c32ff10aaa424864d6fc92b987322 | samsungctl/remote_legacy.py | python | RemoteLegacy.__init__ | (self, config) | Make a new connection. | Make a new connection. | [
"Make",
"a",
"new",
"connection",
"."
] | def __init__(self, config):
if not config["port"]:
config["port"] = 55000
"""Make a new connection."""
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if config["timeout"]:
self.connection.settimeout(config["timeout"])
self.connection.connect((config["host"], config["port"]))
payload = b"\x64\x00" \
+ self._serialize_string(config["description"]) \
+ self._serialize_string(config["id"]) \
+ self._serialize_string(config["name"])
packet = b"\x00\x00\x00" + self._serialize_string(payload, True)
logging.info("Sending handshake.")
self.connection.send(packet)
self._read_response(True) | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"if",
"not",
"config",
"[",
"\"port\"",
"]",
":",
"config",
"[",
"\"port\"",
"]",
"=",
"55000",
"self",
".",
"connection",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"if",
"config",
"[",
"\"timeout\"",
"]",
":",
"self",
".",
"connection",
".",
"settimeout",
"(",
"config",
"[",
"\"timeout\"",
"]",
")",
"self",
".",
"connection",
".",
"connect",
"(",
"(",
"config",
"[",
"\"host\"",
"]",
",",
"config",
"[",
"\"port\"",
"]",
")",
")",
"payload",
"=",
"b\"\\x64\\x00\"",
"+",
"self",
".",
"_serialize_string",
"(",
"config",
"[",
"\"description\"",
"]",
")",
"+",
"self",
".",
"_serialize_string",
"(",
"config",
"[",
"\"id\"",
"]",
")",
"+",
"self",
".",
"_serialize_string",
"(",
"config",
"[",
"\"name\"",
"]",
")",
"packet",
"=",
"b\"\\x00\\x00\\x00\"",
"+",
"self",
".",
"_serialize_string",
"(",
"payload",
",",
"True",
")",
"logging",
".",
"info",
"(",
"\"Sending handshake.\"",
")",
"self",
".",
"connection",
".",
"send",
"(",
"packet",
")",
"self",
".",
"_read_response",
"(",
"True",
")"
] | https://github.com/Ape/samsungctl/blob/81cf14aa138c32ff10aaa424864d6fc92b987322/samsungctl/remote_legacy.py#L12-L32 |
||
Ape/samsungctl | 81cf14aa138c32ff10aaa424864d6fc92b987322 | samsungctl/remote_legacy.py | python | RemoteLegacy.close | (self) | Close the connection. | Close the connection. | [
"Close",
"the",
"connection",
"."
] | def close(self):
"""Close the connection."""
if self.connection:
self.connection.close()
self.connection = None
logging.debug("Connection closed.") | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
":",
"self",
".",
"connection",
".",
"close",
"(",
")",
"self",
".",
"connection",
"=",
"None",
"logging",
".",
"debug",
"(",
"\"Connection closed.\"",
")"
] | https://github.com/Ape/samsungctl/blob/81cf14aa138c32ff10aaa424864d6fc92b987322/samsungctl/remote_legacy.py#L40-L45 |
||
Ape/samsungctl | 81cf14aa138c32ff10aaa424864d6fc92b987322 | samsungctl/remote_legacy.py | python | RemoteLegacy.control | (self, key) | Send a control command. | Send a control command. | [
"Send",
"a",
"control",
"command",
"."
] | def control(self, key):
"""Send a control command."""
if not self.connection:
raise exceptions.ConnectionClosed()
payload = b"\x00\x00\x00" + self._serialize_string(key)
packet = b"\x00\x00\x00" + self._serialize_string(payload, True)
logging.info("Sending control command: %s", key)
self.connection.send(packet)
self._read_response()
time.sleep(self._key_interval) | [
"def",
"control",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"connection",
":",
"raise",
"exceptions",
".",
"ConnectionClosed",
"(",
")",
"payload",
"=",
"b\"\\x00\\x00\\x00\"",
"+",
"self",
".",
"_serialize_string",
"(",
"key",
")",
"packet",
"=",
"b\"\\x00\\x00\\x00\"",
"+",
"self",
".",
"_serialize_string",
"(",
"payload",
",",
"True",
")",
"logging",
".",
"info",
"(",
"\"Sending control command: %s\"",
",",
"key",
")",
"self",
".",
"connection",
".",
"send",
"(",
"packet",
")",
"self",
".",
"_read_response",
"(",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_key_interval",
")"
] | https://github.com/Ape/samsungctl/blob/81cf14aa138c32ff10aaa424864d6fc92b987322/samsungctl/remote_legacy.py#L47-L58 |
||
Ape/samsungctl | 81cf14aa138c32ff10aaa424864d6fc92b987322 | samsungctl/interactive.py | python | run | (remote) | Run interactive remote control application. | Run interactive remote control application. | [
"Run",
"interactive",
"remote",
"control",
"application",
"."
] | def run(remote):
"""Run interactive remote control application."""
curses.wrapper(_control, remote) | [
"def",
"run",
"(",
"remote",
")",
":",
"curses",
".",
"wrapper",
"(",
"_control",
",",
"remote",
")"
] | https://github.com/Ape/samsungctl/blob/81cf14aa138c32ff10aaa424864d6fc92b987322/samsungctl/interactive.py#L45-L47 |
||
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.addDevice | (self, device_name) | return self._request("POST", HOST + "/devices", data) | Push a note
https://docs.pushbullet.com/v2/pushes
Arguments:
device_name -- Human readable name for device
type -- stream, thats all there is currently | Push a note
https://docs.pushbullet.com/v2/pushes | [
"Push",
"a",
"note",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def addDevice(self, device_name):
""" Push a note
https://docs.pushbullet.com/v2/pushes
Arguments:
device_name -- Human readable name for device
type -- stream, thats all there is currently
"""
data = {"nickname": device_name,
"type": "stream"
}
return self._request("POST", HOST + "/devices", data) | [
"def",
"addDevice",
"(",
"self",
",",
"device_name",
")",
":",
"data",
"=",
"{",
"\"nickname\"",
":",
"device_name",
",",
"\"type\"",
":",
"\"stream\"",
"}",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"HOST",
"+",
"\"/devices\"",
",",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L46-L59 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.getDevices | (self) | return self._request("GET", HOST + "/devices")["devices"] | Get devices
https://docs.pushbullet.com/v2/devices
Get a list of devices, and data about them. | Get devices
https://docs.pushbullet.com/v2/devices | [
"Get",
"devices",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"devices"
] | def getDevices(self):
""" Get devices
https://docs.pushbullet.com/v2/devices
Get a list of devices, and data about them.
"""
return self._request("GET", HOST + "/devices")["devices"] | [
"def",
"getDevices",
"(",
"self",
")",
":",
"return",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"HOST",
"+",
"\"/devices\"",
")",
"[",
"\"devices\"",
"]"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L61-L68 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.deleteDevice | (self, device_iden) | return self._request("DELETE", HOST + "/devices/" + device_iden) | Delete a device
https://docs.pushbullet.com/v2/devices
Arguments:
device_iden -- iden of device to push to | Delete a device
https://docs.pushbullet.com/v2/devices | [
"Delete",
"a",
"device",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"devices"
] | def deleteDevice(self, device_iden):
""" Delete a device
https://docs.pushbullet.com/v2/devices
Arguments:
device_iden -- iden of device to push to
"""
return self._request("DELETE", HOST + "/devices/" + device_iden) | [
"def",
"deleteDevice",
"(",
"self",
",",
"device_iden",
")",
":",
"return",
"self",
".",
"_request",
"(",
"\"DELETE\"",
",",
"HOST",
"+",
"\"/devices/\"",
"+",
"device_iden",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L70-L78 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.pushNote | (self, recipient, title, body, recipient_type="device_iden") | return self._request("POST", HOST + "/pushes", data) | Push a note
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
title -- a title for the note
body -- the body of the note
recipient_type -- a type of recipient (device, email, channel or client) | Push a note
https://docs.pushbullet.com/v2/pushes | [
"Push",
"a",
"note",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def pushNote(self, recipient, title, body, recipient_type="device_iden"):
""" Push a note
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
title -- a title for the note
body -- the body of the note
recipient_type -- a type of recipient (device, email, channel or client)
"""
data = {"type": "note",
"title": title,
"body": body}
data[recipient_type] = recipient
return self._request("POST", HOST + "/pushes", data) | [
"def",
"pushNote",
"(",
"self",
",",
"recipient",
",",
"title",
",",
"body",
",",
"recipient_type",
"=",
"\"device_iden\"",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"note\"",
",",
"\"title\"",
":",
"title",
",",
"\"body\"",
":",
"body",
"}",
"data",
"[",
"recipient_type",
"]",
"=",
"recipient",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"HOST",
"+",
"\"/pushes\"",
",",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L80-L97 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.pushAddress | (self, recipient, name, address, recipient_type="device_iden") | return self._request("POST", HOST + "/pushes", data) | Push an address
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
name -- name for the address, eg "Bobs house"
address -- address of the address
recipient_type -- a type of recipient (device, email, channel or client) | Push an address
https://docs.pushbullet.com/v2/pushes | [
"Push",
"an",
"address",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def pushAddress(self, recipient, name, address, recipient_type="device_iden"):
""" Push an address
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
name -- name for the address, eg "Bobs house"
address -- address of the address
recipient_type -- a type of recipient (device, email, channel or client)
"""
data = {"type": "address",
"name": name,
"address": address}
data[recipient_type] = recipient
return self._request("POST", HOST + "/pushes", data) | [
"def",
"pushAddress",
"(",
"self",
",",
"recipient",
",",
"name",
",",
"address",
",",
"recipient_type",
"=",
"\"device_iden\"",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"address\"",
",",
"\"name\"",
":",
"name",
",",
"\"address\"",
":",
"address",
"}",
"data",
"[",
"recipient_type",
"]",
"=",
"recipient",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"HOST",
"+",
"\"/pushes\"",
",",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L99-L116 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.pushList | (self, recipient, title, items, recipient_type="device_iden") | return self._request("POST", HOST + "/pushes", data) | Push a list
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
title -- a title for the list
items -- a list of items
recipient_type -- a type of recipient (device, email, channel or client) | Push a list
https://docs.pushbullet.com/v2/pushes | [
"Push",
"a",
"list",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def pushList(self, recipient, title, items, recipient_type="device_iden"):
""" Push a list
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
title -- a title for the list
items -- a list of items
recipient_type -- a type of recipient (device, email, channel or client)
"""
data = {"type": "list",
"title": title,
"items": items}
data[recipient_type] = recipient
return self._request("POST", HOST + "/pushes", data) | [
"def",
"pushList",
"(",
"self",
",",
"recipient",
",",
"title",
",",
"items",
",",
"recipient_type",
"=",
"\"device_iden\"",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"list\"",
",",
"\"title\"",
":",
"title",
",",
"\"items\"",
":",
"items",
"}",
"data",
"[",
"recipient_type",
"]",
"=",
"recipient",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"HOST",
"+",
"\"/pushes\"",
",",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L118-L135 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.pushLink | (self, recipient, title, url, recipient_type="device_iden") | return self._request("POST", HOST + "/pushes", data) | Push a link
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
title -- link title
url -- link url
recipient_type -- a type of recipient (device, email, channel or client) | Push a link
https://docs.pushbullet.com/v2/pushes | [
"Push",
"a",
"link",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def pushLink(self, recipient, title, url, recipient_type="device_iden"):
""" Push a link
https://docs.pushbullet.com/v2/pushes
Arguments:
recipient -- a recipient
title -- link title
url -- link url
recipient_type -- a type of recipient (device, email, channel or client)
"""
data = {"type": "link",
"title": title,
"url": url}
data[recipient_type] = recipient
return self._request("POST", HOST + "/pushes", data) | [
"def",
"pushLink",
"(",
"self",
",",
"recipient",
",",
"title",
",",
"url",
",",
"recipient_type",
"=",
"\"device_iden\"",
")",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"link\"",
",",
"\"title\"",
":",
"title",
",",
"\"url\"",
":",
"url",
"}",
"data",
"[",
"recipient_type",
"]",
"=",
"recipient",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"HOST",
"+",
"\"/pushes\"",
",",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L137-L154 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.pushFile | (self, recipient, file_name, body, file, file_type=None, recipient_type="device_iden") | return self._request("POST", HOST + "/pushes", data) | Push a file
https://docs.pushbullet.com/v2/pushes
https://docs.pushbullet.com/v2/upload-request
Arguments:
recipient -- a recipient
file_name -- name of the file
file -- a file object
file_type -- file mimetype, if not set, python-magic will be used
recipient_type -- a type of recipient (device, email, channel or client) | Push a file
https://docs.pushbullet.com/v2/pushes
https://docs.pushbullet.com/v2/upload-request | [
"Push",
"a",
"file",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"upload",
"-",
"request"
] | def pushFile(self, recipient, file_name, body, file, file_type=None, recipient_type="device_iden"):
""" Push a file
https://docs.pushbullet.com/v2/pushes
https://docs.pushbullet.com/v2/upload-request
Arguments:
recipient -- a recipient
file_name -- name of the file
file -- a file object
file_type -- file mimetype, if not set, python-magic will be used
recipient_type -- a type of recipient (device, email, channel or client)
"""
if not file_type:
try:
import magic
except ImportError:
raise Exception("No file_type given and python-magic isn't installed")
# Unfortunately there's two libraries called magic, both of which do
# the exact same thing but have different conventions for doing so
if hasattr(magic, "from_buffer"):
file_type = magic.from_buffer(file.read(1024))
else:
_magic = magic.open(magic.MIME_TYPE)
_magic.compile(None)
file_type = _magic.file(file_name)
_magic.close()
file.seek(0)
data = {"file_name": file_name,
"file_type": file_type}
upload_request = self._request("GET",
HOST + "/upload-request",
None,
data)
upload = requests.post(upload_request["upload_url"],
data=upload_request["data"],
files={"file": file},
headers={"User-Agent": "pyPushBullet"})
upload.raise_for_status()
data = {"type": "file",
"file_name": file_name,
"file_type": file_type,
"file_url": upload_request["file_url"],
"body": body}
data[recipient_type] = recipient
return self._request("POST", HOST + "/pushes", data) | [
"def",
"pushFile",
"(",
"self",
",",
"recipient",
",",
"file_name",
",",
"body",
",",
"file",
",",
"file_type",
"=",
"None",
",",
"recipient_type",
"=",
"\"device_iden\"",
")",
":",
"if",
"not",
"file_type",
":",
"try",
":",
"import",
"magic",
"except",
"ImportError",
":",
"raise",
"Exception",
"(",
"\"No file_type given and python-magic isn't installed\"",
")",
"# Unfortunately there's two libraries called magic, both of which do",
"# the exact same thing but have different conventions for doing so",
"if",
"hasattr",
"(",
"magic",
",",
"\"from_buffer\"",
")",
":",
"file_type",
"=",
"magic",
".",
"from_buffer",
"(",
"file",
".",
"read",
"(",
"1024",
")",
")",
"else",
":",
"_magic",
"=",
"magic",
".",
"open",
"(",
"magic",
".",
"MIME_TYPE",
")",
"_magic",
".",
"compile",
"(",
"None",
")",
"file_type",
"=",
"_magic",
".",
"file",
"(",
"file_name",
")",
"_magic",
".",
"close",
"(",
")",
"file",
".",
"seek",
"(",
"0",
")",
"data",
"=",
"{",
"\"file_name\"",
":",
"file_name",
",",
"\"file_type\"",
":",
"file_type",
"}",
"upload_request",
"=",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"HOST",
"+",
"\"/upload-request\"",
",",
"None",
",",
"data",
")",
"upload",
"=",
"requests",
".",
"post",
"(",
"upload_request",
"[",
"\"upload_url\"",
"]",
",",
"data",
"=",
"upload_request",
"[",
"\"data\"",
"]",
",",
"files",
"=",
"{",
"\"file\"",
":",
"file",
"}",
",",
"headers",
"=",
"{",
"\"User-Agent\"",
":",
"\"pyPushBullet\"",
"}",
")",
"upload",
".",
"raise_for_status",
"(",
")",
"data",
"=",
"{",
"\"type\"",
":",
"\"file\"",
",",
"\"file_name\"",
":",
"file_name",
",",
"\"file_type\"",
":",
"file_type",
",",
"\"file_url\"",
":",
"upload_request",
"[",
"\"file_url\"",
"]",
",",
"\"body\"",
":",
"body",
"}",
"data",
"[",
"recipient_type",
"]",
"=",
"recipient",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"HOST",
"+",
"\"/pushes\"",
",",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L156-L212 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.getPushHistory | (self, modified_after=0, cursor=None) | return self._request("GET", HOST + "/pushes", None, data)["pushes"] | Get Push History
https://docs.pushbullet.com/v2/pushes
Returns a list of pushes
Arguments:
modified_after -- Request pushes modified after this timestamp
cursor -- Request another page of pushes (if necessary) | Get Push History
https://docs.pushbullet.com/v2/pushes | [
"Get",
"Push",
"History",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def getPushHistory(self, modified_after=0, cursor=None):
""" Get Push History
https://docs.pushbullet.com/v2/pushes
Returns a list of pushes
Arguments:
modified_after -- Request pushes modified after this timestamp
cursor -- Request another page of pushes (if necessary)
"""
data = {"modified_after": modified_after}
if cursor:
data["cursor"] = cursor
return self._request("GET", HOST + "/pushes", None, data)["pushes"] | [
"def",
"getPushHistory",
"(",
"self",
",",
"modified_after",
"=",
"0",
",",
"cursor",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"modified_after\"",
":",
"modified_after",
"}",
"if",
"cursor",
":",
"data",
"[",
"\"cursor\"",
"]",
"=",
"cursor",
"return",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"HOST",
"+",
"\"/pushes\"",
",",
"None",
",",
"data",
")",
"[",
"\"pushes\"",
"]"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L214-L227 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.deletePush | (self, push_iden) | return self._request("DELETE", HOST + "/pushes/" + push_iden) | Delete push
https://docs.pushbullet.com/v2/pushes
Arguments:
push_iden -- the iden of the push to delete | Delete push
https://docs.pushbullet.com/v2/pushes | [
"Delete",
"push",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def deletePush(self, push_iden):
""" Delete push
https://docs.pushbullet.com/v2/pushes
Arguments:
push_iden -- the iden of the push to delete
"""
return self._request("DELETE", HOST + "/pushes/" + push_iden) | [
"def",
"deletePush",
"(",
"self",
",",
"push_iden",
")",
":",
"return",
"self",
".",
"_request",
"(",
"\"DELETE\"",
",",
"HOST",
"+",
"\"/pushes/\"",
"+",
"push_iden",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L229-L236 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.getContacts | (self) | return self._request("GET", HOST + "/contacts")["contacts"] | Gets your contacts
https://docs.pushbullet.com/v2/contacts
returns a list of contacts | Gets your contacts
https://docs.pushbullet.com/v2/contacts | [
"Gets",
"your",
"contacts",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"contacts"
] | def getContacts(self):
""" Gets your contacts
https://docs.pushbullet.com/v2/contacts
returns a list of contacts
"""
return self._request("GET", HOST + "/contacts")["contacts"] | [
"def",
"getContacts",
"(",
"self",
")",
":",
"return",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"HOST",
"+",
"\"/contacts\"",
")",
"[",
"\"contacts\"",
"]"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L238-L244 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.deleteContact | (self, contact_iden) | return self._request("DELETE", HOST + "/contacts/" + contact_iden) | Delete a contact
https://docs.pushbullet.com/v2/contacts
Arguments:
contact_iden -- the iden of the contact to delete | Delete a contact
https://docs.pushbullet.com/v2/contacts | [
"Delete",
"a",
"contact",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"contacts"
] | def deleteContact(self, contact_iden):
""" Delete a contact
https://docs.pushbullet.com/v2/contacts
Arguments:
contact_iden -- the iden of the contact to delete
"""
return self._request("DELETE", HOST + "/contacts/" + contact_iden) | [
"def",
"deleteContact",
"(",
"self",
",",
"contact_iden",
")",
":",
"return",
"self",
".",
"_request",
"(",
"\"DELETE\"",
",",
"HOST",
"+",
"\"/contacts/\"",
"+",
"contact_iden",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L246-L253 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.getUser | (self) | return self._request("GET", HOST + "/users/me") | Get this users information
https://docs.pushbullet.com/v2/users | Get this users information
https://docs.pushbullet.com/v2/users | [
"Get",
"this",
"users",
"information",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"users"
] | def getUser(self):
""" Get this users information
https://docs.pushbullet.com/v2/users
"""
return self._request("GET", HOST + "/users/me") | [
"def",
"getUser",
"(",
"self",
")",
":",
"return",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"HOST",
"+",
"\"/users/me\"",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L255-L259 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.dismissEphemeral | (self, notification_id, notification_tag, package_name, source_user_iden) | return self._request("POST", HOST + "/ephemerals", data) | Marks an ephemeral notification as dismissed
https://docs.pushbullet.com/v2/pushes
Arguments:
notification_id -- the id of the notification to dismiss
notification_tag -- the tag of the notification
package_name -- the name of the package that made the notification
source_user_iden -- the identifier for the user that made the notification | Marks an ephemeral notification as dismissed
https://docs.pushbullet.com/v2/pushes | [
"Marks",
"an",
"ephemeral",
"notification",
"as",
"dismissed",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"v2",
"/",
"pushes"
] | def dismissEphemeral(self, notification_id, notification_tag, package_name, source_user_iden):
""" Marks an ephemeral notification as dismissed
https://docs.pushbullet.com/v2/pushes
Arguments:
notification_id -- the id of the notification to dismiss
notification_tag -- the tag of the notification
package_name -- the name of the package that made the notification
source_user_iden -- the identifier for the user that made the notification
"""
data = {"push": {"notification_id": notification_id,
"notification_tag": notification_tag,
"package_name": package_name,
"source_user_iden": source_user_iden,
"type": "dismissal"},
"type": "push"}
return self._request("POST", HOST + "/ephemerals", data) | [
"def",
"dismissEphemeral",
"(",
"self",
",",
"notification_id",
",",
"notification_tag",
",",
"package_name",
",",
"source_user_iden",
")",
":",
"data",
"=",
"{",
"\"push\"",
":",
"{",
"\"notification_id\"",
":",
"notification_id",
",",
"\"notification_tag\"",
":",
"notification_tag",
",",
"\"package_name\"",
":",
"package_name",
",",
"\"source_user_iden\"",
":",
"source_user_iden",
",",
"\"type\"",
":",
"\"dismissal\"",
"}",
",",
"\"type\"",
":",
"\"push\"",
"}",
"return",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"HOST",
"+",
"\"/ephemerals\"",
",",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L261-L278 |
|
Azelphur/pyPushBullet | d230d80419f105367dade9337539dd112d574869 | pushbullet/pushbullet.py | python | PushBullet.realtime | (self, callback) | Opens a Realtime Event Stream
https://docs.pushbullet.com/stream
callback will be called with one argument, the JSON response
from the server, nop messages are filtered.
Arguments:
callback -- The function to call on activity | Opens a Realtime Event Stream
https://docs.pushbullet.com/stream | [
"Opens",
"a",
"Realtime",
"Event",
"Stream",
"https",
":",
"//",
"docs",
".",
"pushbullet",
".",
"com",
"/",
"stream"
] | def realtime(self, callback):
""" Opens a Realtime Event Stream
https://docs.pushbullet.com/stream
callback will be called with one argument, the JSON response
from the server, nop messages are filtered.
Arguments:
callback -- The function to call on activity
"""
url = "wss://stream.pushbullet.com/websocket/" + self.apiKey
ws = create_connection(url)
while 1:
data = ws.recv()
data = json.loads(data)
if data["type"] != "nop":
callback(data) | [
"def",
"realtime",
"(",
"self",
",",
"callback",
")",
":",
"url",
"=",
"\"wss://stream.pushbullet.com/websocket/\"",
"+",
"self",
".",
"apiKey",
"ws",
"=",
"create_connection",
"(",
"url",
")",
"while",
"1",
":",
"data",
"=",
"ws",
".",
"recv",
"(",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"if",
"data",
"[",
"\"type\"",
"]",
"!=",
"\"nop\"",
":",
"callback",
"(",
"data",
")"
] | https://github.com/Azelphur/pyPushBullet/blob/d230d80419f105367dade9337539dd112d574869/pushbullet/pushbullet.py#L280-L297 |
||
BIGBALLON/CIFAR-ZOO | 94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5 | utils.py | python | mixup_data | (x, y, alpha, device) | return mixed_x, y_a, y_b, lam | Returns mixed inputs, pairs of targets, and lambda | Returns mixed inputs, pairs of targets, and lambda | [
"Returns",
"mixed",
"inputs",
"pairs",
"of",
"targets",
"and",
"lambda"
] | def mixup_data(x, y, alpha, device):
"""Returns mixed inputs, pairs of targets, and lambda"""
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
batch_size = x.size()[0]
index = torch.randperm(batch_size).to(device)
mixed_x = lam * x + (1 - lam) * x[index, :]
y_a, y_b = y, y[index]
return mixed_x, y_a, y_b, lam | [
"def",
"mixup_data",
"(",
"x",
",",
"y",
",",
"alpha",
",",
"device",
")",
":",
"if",
"alpha",
">",
"0",
":",
"lam",
"=",
"np",
".",
"random",
".",
"beta",
"(",
"alpha",
",",
"alpha",
")",
"else",
":",
"lam",
"=",
"1",
"batch_size",
"=",
"x",
".",
"size",
"(",
")",
"[",
"0",
"]",
"index",
"=",
"torch",
".",
"randperm",
"(",
"batch_size",
")",
".",
"to",
"(",
"device",
")",
"mixed_x",
"=",
"lam",
"*",
"x",
"+",
"(",
"1",
"-",
"lam",
")",
"*",
"x",
"[",
"index",
",",
":",
"]",
"y_a",
",",
"y_b",
"=",
"y",
",",
"y",
"[",
"index",
"]",
"return",
"mixed_x",
",",
"y_a",
",",
"y_b",
",",
"lam"
] | https://github.com/BIGBALLON/CIFAR-ZOO/blob/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5/utils.py#L147-L159 |
|
BIGBALLON/CIFAR-ZOO | 94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5 | models/sknet.py | python | SKConv.__init__ | (self, features, M, G, r, stride=1, L=32) | Constructor
Args:
features: input channel dimensionality.
M: the number of branchs.
G: num of convolution groups.
r: the radio for compute d, the length of z.
stride: stride, default 1.
L: the minimum dim of the vector z in paper, default 32. | Constructor
Args:
features: input channel dimensionality.
M: the number of branchs.
G: num of convolution groups.
r: the radio for compute d, the length of z.
stride: stride, default 1.
L: the minimum dim of the vector z in paper, default 32. | [
"Constructor",
"Args",
":",
"features",
":",
"input",
"channel",
"dimensionality",
".",
"M",
":",
"the",
"number",
"of",
"branchs",
".",
"G",
":",
"num",
"of",
"convolution",
"groups",
".",
"r",
":",
"the",
"radio",
"for",
"compute",
"d",
"the",
"length",
"of",
"z",
".",
"stride",
":",
"stride",
"default",
"1",
".",
"L",
":",
"the",
"minimum",
"dim",
"of",
"the",
"vector",
"z",
"in",
"paper",
"default",
"32",
"."
] | def __init__(self, features, M, G, r, stride=1, L=32):
""" Constructor
Args:
features: input channel dimensionality.
M: the number of branchs.
G: num of convolution groups.
r: the radio for compute d, the length of z.
stride: stride, default 1.
L: the minimum dim of the vector z in paper, default 32.
"""
super(SKConv, self).__init__()
d = max(int(features / r), L)
self.convs = nn.ModuleList([])
for i in range(M):
self.convs.append(
nn.Sequential(
nn.Conv2d(
features,
features,
kernel_size=1 + i * 2,
stride=stride,
padding=i,
groups=G,
),
nn.BatchNorm2d(features),
nn.ReLU(inplace=False),
)
)
self.gap = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Linear(features, d)
self.fcs = nn.ModuleList([])
for i in range(M):
self.fcs.append(nn.Linear(d, features))
self.softmax = nn.Softmax(dim=1) | [
"def",
"__init__",
"(",
"self",
",",
"features",
",",
"M",
",",
"G",
",",
"r",
",",
"stride",
"=",
"1",
",",
"L",
"=",
"32",
")",
":",
"super",
"(",
"SKConv",
",",
"self",
")",
".",
"__init__",
"(",
")",
"d",
"=",
"max",
"(",
"int",
"(",
"features",
"/",
"r",
")",
",",
"L",
")",
"self",
".",
"convs",
"=",
"nn",
".",
"ModuleList",
"(",
"[",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"M",
")",
":",
"self",
".",
"convs",
".",
"append",
"(",
"nn",
".",
"Sequential",
"(",
"nn",
".",
"Conv2d",
"(",
"features",
",",
"features",
",",
"kernel_size",
"=",
"1",
"+",
"i",
"*",
"2",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"i",
",",
"groups",
"=",
"G",
",",
")",
",",
"nn",
".",
"BatchNorm2d",
"(",
"features",
")",
",",
"nn",
".",
"ReLU",
"(",
"inplace",
"=",
"False",
")",
",",
")",
")",
"self",
".",
"gap",
"=",
"nn",
".",
"AdaptiveAvgPool2d",
"(",
"1",
")",
"self",
".",
"fc",
"=",
"nn",
".",
"Linear",
"(",
"features",
",",
"d",
")",
"self",
".",
"fcs",
"=",
"nn",
".",
"ModuleList",
"(",
"[",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"M",
")",
":",
"self",
".",
"fcs",
".",
"append",
"(",
"nn",
".",
"Linear",
"(",
"d",
",",
"features",
")",
")",
"self",
".",
"softmax",
"=",
"nn",
".",
"Softmax",
"(",
"dim",
"=",
"1",
")"
] | https://github.com/BIGBALLON/CIFAR-ZOO/blob/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5/models/sknet.py#L10-L43 |
||
BIGBALLON/CIFAR-ZOO | 94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5 | models/resnext.py | python | ResNeXt.__init__ | (self, cardinality, depth, num_classes, base_width, expansion=4) | Constructor
Args:
cardinality: number of convolution groups.
depth: number of layers.
num_classes: number of classes
base_width: base number of channels in each group.
expansion: factor to adjust the channel dimensionality | Constructor
Args:
cardinality: number of convolution groups.
depth: number of layers.
num_classes: number of classes
base_width: base number of channels in each group.
expansion: factor to adjust the channel dimensionality | [
"Constructor",
"Args",
":",
"cardinality",
":",
"number",
"of",
"convolution",
"groups",
".",
"depth",
":",
"number",
"of",
"layers",
".",
"num_classes",
":",
"number",
"of",
"classes",
"base_width",
":",
"base",
"number",
"of",
"channels",
"in",
"each",
"group",
".",
"expansion",
":",
"factor",
"to",
"adjust",
"the",
"channel",
"dimensionality"
] | def __init__(self, cardinality, depth, num_classes, base_width, expansion=4):
""" Constructor
Args:
cardinality: number of convolution groups.
depth: number of layers.
num_classes: number of classes
base_width: base number of channels in each group.
expansion: factor to adjust the channel dimensionality
"""
super(ResNeXt, self).__init__()
self.cardinality = cardinality
self.depth = depth
self.block_depth = (self.depth - 2) // 9
self.base_width = base_width
self.expansion = expansion
self.num_classes = num_classes
self.output_size = 64
self.stages = [
64,
64 * self.expansion,
128 * self.expansion,
256 * self.expansion,
]
self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)
self.bn_1 = nn.BatchNorm2d(64)
self.stage_1 = self.block("stage_1", self.stages[0], self.stages[1], 1)
self.stage_2 = self.block("stage_2", self.stages[1], self.stages[2], 2)
self.stage_3 = self.block("stage_3", self.stages[2], self.stages[3], 2)
self.fc = nn.Linear(self.stages[3], num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight.data)
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_() | [
"def",
"__init__",
"(",
"self",
",",
"cardinality",
",",
"depth",
",",
"num_classes",
",",
"base_width",
",",
"expansion",
"=",
"4",
")",
":",
"super",
"(",
"ResNeXt",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"cardinality",
"=",
"cardinality",
"self",
".",
"depth",
"=",
"depth",
"self",
".",
"block_depth",
"=",
"(",
"self",
".",
"depth",
"-",
"2",
")",
"//",
"9",
"self",
".",
"base_width",
"=",
"base_width",
"self",
".",
"expansion",
"=",
"expansion",
"self",
".",
"num_classes",
"=",
"num_classes",
"self",
".",
"output_size",
"=",
"64",
"self",
".",
"stages",
"=",
"[",
"64",
",",
"64",
"*",
"self",
".",
"expansion",
",",
"128",
"*",
"self",
".",
"expansion",
",",
"256",
"*",
"self",
".",
"expansion",
",",
"]",
"self",
".",
"conv_1_3x3",
"=",
"nn",
".",
"Conv2d",
"(",
"3",
",",
"64",
",",
"3",
",",
"1",
",",
"1",
",",
"bias",
"=",
"False",
")",
"self",
".",
"bn_1",
"=",
"nn",
".",
"BatchNorm2d",
"(",
"64",
")",
"self",
".",
"stage_1",
"=",
"self",
".",
"block",
"(",
"\"stage_1\"",
",",
"self",
".",
"stages",
"[",
"0",
"]",
",",
"self",
".",
"stages",
"[",
"1",
"]",
",",
"1",
")",
"self",
".",
"stage_2",
"=",
"self",
".",
"block",
"(",
"\"stage_2\"",
",",
"self",
".",
"stages",
"[",
"1",
"]",
",",
"self",
".",
"stages",
"[",
"2",
"]",
",",
"2",
")",
"self",
".",
"stage_3",
"=",
"self",
".",
"block",
"(",
"\"stage_3\"",
",",
"self",
".",
"stages",
"[",
"2",
"]",
",",
"self",
".",
"stages",
"[",
"3",
"]",
",",
"2",
")",
"self",
".",
"fc",
"=",
"nn",
".",
"Linear",
"(",
"self",
".",
"stages",
"[",
"3",
"]",
",",
"num_classes",
")",
"for",
"m",
"in",
"self",
".",
"modules",
"(",
")",
":",
"if",
"isinstance",
"(",
"m",
",",
"nn",
".",
"Conv2d",
")",
":",
"nn",
".",
"init",
".",
"kaiming_normal_",
"(",
"m",
".",
"weight",
".",
"data",
")",
"elif",
"isinstance",
"(",
"m",
",",
"nn",
".",
"BatchNorm2d",
")",
":",
"m",
".",
"weight",
".",
"data",
".",
"fill_",
"(",
"1",
")",
"m",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")"
] | https://github.com/BIGBALLON/CIFAR-ZOO/blob/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5/models/resnext.py#L70-L105 |
||
BIGBALLON/CIFAR-ZOO | 94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5 | models/preresnet.py | python | conv3x3 | (in_planes, out_planes, stride=1) | return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
) | 3x3 convolution with padding | 3x3 convolution with padding | [
"3x3",
"convolution",
"with",
"padding"
] | def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
"False",
")"
] | https://github.com/BIGBALLON/CIFAR-ZOO/blob/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5/models/preresnet.py#L15-L19 |
|
BIGBALLON/CIFAR-ZOO | 94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5 | models/resnet.py | python | conv3x3 | (in_planes, out_planes, stride=1) | return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
) | 3x3 convolution with padding | 3x3 convolution with padding | [
"3x3",
"convolution",
"with",
"padding"
] | def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
"False",
")"
] | https://github.com/BIGBALLON/CIFAR-ZOO/blob/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5/models/resnet.py#L8-L12 |
|
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_270.py | python | util_is_header_valid | (filename, file_ext, chunk_id, error_callback) | return True | Return True if chunk_id is a valid psk/psa (file_ext) 'magick number'. | Return True if chunk_id is a valid psk/psa (file_ext) 'magick number'. | [
"Return",
"True",
"if",
"chunk_id",
"is",
"a",
"valid",
"psk",
"/",
"psa",
"(",
"file_ext",
")",
"magick",
"number",
"."
] | def util_is_header_valid(filename, file_ext, chunk_id, error_callback):
'''Return True if chunk_id is a valid psk/psa (file_ext) 'magick number'.'''
if chunk_id != PSKPSA_FILE_HEADER[file_ext]:
error_callback(
"File %s is not a %s file. (header mismach)\nExpected: %s \nPresent %s" % (
filename, file_ext,
PSKPSA_FILE_HEADER[file_ext], chunk_id)
)
return False
return True | [
"def",
"util_is_header_valid",
"(",
"filename",
",",
"file_ext",
",",
"chunk_id",
",",
"error_callback",
")",
":",
"if",
"chunk_id",
"!=",
"PSKPSA_FILE_HEADER",
"[",
"file_ext",
"]",
":",
"error_callback",
"(",
"\"File %s is not a %s file. (header mismach)\\nExpected: %s \\nPresent %s\"",
"%",
"(",
"filename",
",",
"file_ext",
",",
"PSKPSA_FILE_HEADER",
"[",
"file_ext",
"]",
",",
"chunk_id",
")",
")",
"return",
"False",
"return",
"True"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_270.py#L162-L171 |
|
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_270.py | python | util_gen_name_part | (filepath) | return re.match(r'.*[/\\]([^/\\]+?)(\..{2,5})?$', filepath).group(1) | Return file name without extension | Return file name without extension | [
"Return",
"file",
"name",
"without",
"extension"
] | def util_gen_name_part(filepath):
'''Return file name without extension'''
return re.match(r'.*[/\\]([^/\\]+?)(\..{2,5})?$', filepath).group(1) | [
"def",
"util_gen_name_part",
"(",
"filepath",
")",
":",
"return",
"re",
".",
"match",
"(",
"r'.*[/\\\\]([^/\\\\]+?)(\\..{2,5})?$'",
",",
"filepath",
")",
".",
"group",
"(",
"1",
")"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_270.py#L174-L176 |
|
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_270.py | python | vec_to_axis_vec | (vec_in, vec_out) | Make **vec_out** to be an axis-aligned unit vector that is closest to vec_in. (basis?) | Make **vec_out** to be an axis-aligned unit vector that is closest to vec_in. (basis?) | [
"Make",
"**",
"vec_out",
"**",
"to",
"be",
"an",
"axis",
"-",
"aligned",
"unit",
"vector",
"that",
"is",
"closest",
"to",
"vec_in",
".",
"(",
"basis?",
")"
] | def vec_to_axis_vec(vec_in, vec_out):
'''Make **vec_out** to be an axis-aligned unit vector that is closest to vec_in. (basis?)'''
x, y, z = vec_in
if abs(x) > abs(y):
if abs(x) > abs(z):
vec_out.x = 1 if x >= 0 else -1
else:
vec_out.z = 1 if z >= 0 else -1
else:
if abs(y) > abs(z):
vec_out.y = 1 if y >= 0 else -1
else:
vec_out.z = 1 if z >= 0 else -1 | [
"def",
"vec_to_axis_vec",
"(",
"vec_in",
",",
"vec_out",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"vec_in",
"if",
"abs",
"(",
"x",
")",
">",
"abs",
"(",
"y",
")",
":",
"if",
"abs",
"(",
"x",
")",
">",
"abs",
"(",
"z",
")",
":",
"vec_out",
".",
"x",
"=",
"1",
"if",
"x",
">=",
"0",
"else",
"-",
"1",
"else",
":",
"vec_out",
".",
"z",
"=",
"1",
"if",
"z",
">=",
"0",
"else",
"-",
"1",
"else",
":",
"if",
"abs",
"(",
"y",
")",
">",
"abs",
"(",
"z",
")",
":",
"vec_out",
".",
"y",
"=",
"1",
"if",
"y",
">=",
"0",
"else",
"-",
"1",
"else",
":",
"vec_out",
".",
"z",
"=",
"1",
"if",
"z",
">=",
"0",
"else",
"-",
"1"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_270.py#L179-L191 |
||
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_270.py | python | pskimport | (filepath,
context = bpy.context,
bImportmesh = True,
bImportbone = True,
bSpltiUVdata = False,
fBonesize = 5.0,
fBonesizeRatio = 0.6,
bDontInvertRoot = False,
bReorientBones = False,
bReorientDirectly = False,
error_callback = None) | return True | Import mesh and skeleton from .psk/.pskx files
Args:
bReorientBones:
Axis based bone orientation to children
error_callback:
Called when importing is failed.
__name__('?', error_callback = lambda msg: print('reason:',msg) | Import mesh and skeleton from .psk/.pskx files
Args:
bReorientBones:
Axis based bone orientation to children
error_callback:
Called when importing is failed.
__name__('?', error_callback = lambda msg: print('reason:',msg) | [
"Import",
"mesh",
"and",
"skeleton",
"from",
".",
"psk",
"/",
".",
"pskx",
"files",
"Args",
":",
"bReorientBones",
":",
"Axis",
"based",
"bone",
"orientation",
"to",
"children",
"error_callback",
":",
"Called",
"when",
"importing",
"is",
"failed",
".",
"__name__",
"(",
"?",
"error_callback",
"=",
"lambda",
"msg",
":",
"print",
"(",
"reason",
":",
"msg",
")"
] | def pskimport(filepath,
context = bpy.context,
bImportmesh = True,
bImportbone = True,
bSpltiUVdata = False,
fBonesize = 5.0,
fBonesizeRatio = 0.6,
bDontInvertRoot = False,
bReorientBones = False,
bReorientDirectly = False,
error_callback = None):
'''
Import mesh and skeleton from .psk/.pskx files
Args:
bReorientBones:
Axis based bone orientation to children
error_callback:
Called when importing is failed.
__name__('?', error_callback = lambda msg: print('reason:',msg)
'''
if not hasattr( error_callback, '__call__'):
error_callback = __pass
# ref_time = time.process_time()
if not bImportbone and not bImportmesh:
error_callback("Nothing to do.\nSet something for import.")
return False
file_ext = 'psk'
print ("-----------------------------------------------")
print ("---------EXECUTING PSK PYTHON IMPORTER---------")
print ("-----------------------------------------------")
#file may not exist
try:
file = open(filepath,'rb')
except IOError:
error_callback('Error while opening file for reading:\n "'+filepath+'"')
return False
if not util_check_file_header(file, 'psk'):
error_callback('Not psk file:\n "'+filepath+'"')
return False
Vertices = None
Wedges = None
Faces = None
UV_by_face = None
Materials = None
Bones = None
Weights = None
Extrauvs = []
Normals = None
#==================================================================================================
# Materials MaterialNameRaw | TextureIndex | PolyFlags | AuxMaterial | AuxFlags | LodBias | LodStyle
# Only Name is usable.
def read_materials():
nonlocal Materials
Materials = []
for counter in range(chunk_datacount):
(MaterialNameRaw,) = unpack_from('64s24x', chunk_data, chunk_datasize * counter)
Materials.append( util_bytes_to_str( MaterialNameRaw ) )
#==================================================================================================
# Faces WdgIdx1 | WdgIdx2 | WdgIdx3 | MatIdx | AuxMatIdx | SmthGrp
def read_faces():
nonlocal Faces, UV_by_face
if not bImportmesh:
return True
UV_by_face = [None] * chunk_datacount
Faces = [None] * chunk_datacount
if len(Wedges) > 65536:
unpack_format = '=IIIBBI'
else:
unpack_format = '=HHHBBI'
unpack_data = Struct(unpack_format).unpack_from
for counter in range(chunk_datacount):
(WdgIdx1, WdgIdx2, WdgIdx3,
MatIndex,
AuxMatIndex, #unused
SmoothingGroup # Umodel is not exporting SmoothingGroups
) = unpack_data(chunk_data, counter * chunk_datasize)
# looks ugly
# Wedges is (point_index, u, v, MatIdx)
((vertid0, u0, v0, matid0), (vertid1, u1, v1, matid1), (vertid2, u2, v2, matid2)) = Wedges[WdgIdx1], Wedges[WdgIdx2], Wedges[WdgIdx3]
# note order: C,B,A
Faces[counter] = (vertid2, vertid1, vertid0)
uv = ( ( u2, 1.0 - v2 ), ( u1, 1.0 - v1 ), ( u0, 1.0 - v0 ) )
# Mapping: FaceIndex <=> UV data <=> FaceMatIndex
UV_by_face[counter] = (uv, MatIndex, (matid2, matid1, matid0))
#==================================================================================================
# Vertices X | Y | Z
def read_vertices():
nonlocal bImportbone, bImportmesh
if not bImportmesh:
return True
nonlocal Vertices
Vertices = [None] * chunk_datacount
unpack_data = Struct('3f').unpack_from
for counter in range( chunk_datacount ):
(vec_x, vec_y, vec_z) = unpack_data(chunk_data, counter * chunk_datasize)
Vertices[counter] = (vec_x, vec_y, vec_z)
#==================================================================================================
# Wedges (UV) VertexId | U | V | MatIdx
def read_wedges():
nonlocal bImportbone, bImportmesh
if not bImportmesh:
return True
nonlocal Wedges
Wedges = [None] * chunk_datacount
unpack_data = Struct('=IffBxxx').unpack_from
for counter in range( chunk_datacount ):
(vertex_id,
u, v,
material_index) = unpack_data( chunk_data, counter * chunk_datasize )
# print(vertex_id, u, v, material_index)
# Wedges[counter] = (vertex_id, u, v, material_index)
Wedges[counter] = [vertex_id, u, v, material_index]
#==================================================================================================
# Bones (VBone .. VJointPos ) Name|Flgs|NumChld|PrntIdx|Qw|Qx|Qy|Qz|LocX|LocY|LocZ|Lngth|XSize|YSize|ZSize
def read_bones():
nonlocal Bones, bImportbone
if chunk_datacount == 0:
bImportbone = False
if bImportbone:
unpack_data = Struct('64s3i11f').unpack_from
else:
unpack_data = Struct('64s56x').unpack_from
Bones = [None] * chunk_datacount
for counter in range( chunk_datacount ):
Bones[counter] = unpack_data( chunk_data, chunk_datasize * counter)
#==================================================================================================
# Influences (Bone Weight) (VRawBoneInfluence) ( Weight | PntIdx | BoneIdx)
def read_weights():
# nonlocal Weights, bImportmesh
nonlocal Weights
if not bImportmesh:
return True
Weights = [None] * chunk_datacount
unpack_data = Struct('fii').unpack_from
for counter in range(chunk_datacount):
Weights[counter] = unpack_data(chunk_data, chunk_datasize * counter)
#==================================================================================================
# Extra UV. U | V
def read_extrauvs():
unpack_data = Struct("=2f").unpack_from
uvdata = [None] * chunk_datacount
for counter in range( chunk_datacount ):
uvdata[counter] = unpack_data(chunk_data, chunk_datasize * counter)
Extrauvs.append(uvdata)
#==================================================================================================
# Vertex Normals NX | NY | NZ
def read_normals():
if not bImportmesh:
return True
nonlocal Normals
Normals = [None] * chunk_datacount
unpack_data = Struct('3f').unpack_from
for counter in range(chunk_datacount):
Normals[counter] = unpack_data(chunk_data, counter * chunk_datasize)
CHUNKS_HANDLERS = {
'PNTS0000': read_vertices,
'VTXW0000': read_wedges,
'VTXW3200': read_wedges,#?
'FACE0000': read_faces,
'FACE3200': read_faces,
'MATT0000': read_materials,
'REFSKELT': read_bones,
'REFSKEL0': read_bones, #?
'RAWW0000': read_weights,
'RAWWEIGH': read_weights,
'EXTRAUVS': read_extrauvs,
'VTXNORMS': read_normals
}
#===================================================================================================
# File. Read all needed data.
# VChunkHeader Struct
# ChunkID|TypeFlag|DataSize|DataCount
# 0 |1 |2 |3
while True:
header_bytes = file.read(32)
if len(header_bytes) < 32:
if len(header_bytes) != 0:
error_callback("Unexpected end of file.(%s/32 bytes)" % len(header_bytes))
break
(chunk_id, chunk_type, chunk_datasize, chunk_datacount) = unpack('20s3i', header_bytes)
chunk_id_str = util_bytes_to_str(chunk_id)
chunk_id_str = chunk_id_str[:8]
if chunk_id_str in CHUNKS_HANDLERS:
chunk_data = file.read( chunk_datasize * chunk_datacount)
if len(chunk_data) < chunk_datasize * chunk_datacount:
error_callback('Psk chunk %s is broken.' % chunk_id_str)
return False
CHUNKS_HANDLERS[chunk_id_str]()
else:
print('Unknown chunk: ', chunk_id_str)
file.seek(chunk_datasize * chunk_datacount, 1)
# print(chunk_id_str, chunk_datacount)
file.close()
print(" Importing file:", filepath)
if not bImportmesh and (Bones is None or len(Bones) == 0):
error_callback("Psk: no skeleton data.")
return False
MAX_UVS = 8
NAME_UV_PREFIX = "UV"
# file name w/out extension
gen_name_part = util_gen_name_part(filepath)
gen_names = {
'armature_object': gen_name_part + '.ao',
'armature_data': gen_name_part + '.ad',
'mesh_object': gen_name_part + '.mo',
'mesh_data': gen_name_part + '.md'
}
if bImportmesh:
mesh_data = bpy.data.meshes.new(gen_names['mesh_data'])
mesh_obj = bpy.data.objects.new(gen_names['mesh_object'], mesh_data)
#==================================================================================================
# UV. Prepare
if bImportmesh:
if bSpltiUVdata:
# store how much each "matrial index" have vertices
uv_mat_ids = {}
for (_, _, _, material_index) in Wedges:
if not (material_index in uv_mat_ids):
uv_mat_ids[material_index] = 1
else:
uv_mat_ids[material_index] += 1
# if we have more UV material indexes than blender UV maps, then...
if bSpltiUVdata and len(uv_mat_ids) > MAX_UVS :
uv_mat_ids_len = len(uv_mat_ids)
print('UVs: %s out of %s is combined in a first UV map(%s0)' % (uv_mat_ids_len - 8, uv_mat_ids_len, NAME_UV_PREFIX))
mat_idx_proxy = [0] * len(uv_mat_ids)
counts_sorted = sorted(uv_mat_ids.values(), reverse = True)
new_mat_index = MAX_UVS - 1
for c in counts_sorted:
for mat_idx, counts in uv_mat_ids.items():
if c == counts:
mat_idx_proxy[mat_idx] = new_mat_index
if new_mat_index > 0:
new_mat_index -= 1
# print('MatIdx remap: %s > %s' % (mat_idx,new_mat_index))
for i in range(len(Wedges)):
Wedges[i][3] = mat_idx_proxy[Wedges[i][3]]
# print('Wedges:', chunk_datacount)
# print('uv_mat_ids', uv_mat_ids)
# print('uv_mat_ids', uv_mat_ids)
# for w in Wedges:
if bImportmesh:
# print("-- Materials -- (index, name, faces)")
blen_materials = []
for materialname in Materials:
matdata = bpy.data.materials.get(materialname)
if matdata is None:
matdata = bpy.data.materials.new( materialname )
# matdata = bpy.data.materials.new( materialname )
blen_materials.append( matdata )
mesh_data.materials.append( matdata )
# print(counter,materialname,TextureIndex)
# if mat_groups.get(counter) is not None:
# print("%i: %s" % (counter, materialname), len(mat_groups[counter]))
#==================================================================================================
# Prepare bone data
psk_bone_name_toolong = False
def init_psk_bone(i, psk_bones, name_raw):
psk_bone = class_psk_bone()
psk_bone.children = []
psk_bone.name = util_bytes_to_str(name_raw)
psk_bones[i] = psk_bone
return psk_bone
# indexed by bone index. array of psk_bone
psk_bones = [None] * len(Bones)
if not bImportbone: #data needed for mesh-only import
for counter,(name_raw,) in enumerate(Bones):
init_psk_bone(counter, psk_bones, name_raw)
if bImportbone: #else?
# average bone length
sum_bone_pos = 0
for counter, (name_raw, flags, NumChildren, ParentIndex, #0 1 2 3
quat_x, quat_y, quat_z, quat_w, #4 5 6 7
vec_x, vec_y, vec_z, #8 9 10
joint_length, #11
scale_x, scale_y, scale_z) in enumerate(Bones):
psk_bone = init_psk_bone(counter, psk_bones, name_raw)
psk_bone.bone_index = counter
psk_bone.parent_index = ParentIndex
if len(psk_bone.name) > 60:
psk_bone_name_toolong = True
# print(psk_bone.bone_index, psk_bone.parent_index, psk_bone.name)
# make sure we have valid parent_index
if psk_bone.parent_index < 0:
psk_bone.parent_index = 0
# psk_bone.scale = (scale_x, scale_y, scale_z)
# store bind pose to make it available for psa-import via CustomProperty of the Blender bone
psk_bone.orig_quat = Quaternion((quat_w, quat_x, quat_y, quat_z))
psk_bone.orig_loc = Vector((vec_x, vec_y, vec_z))
# root bone must have parent_index = 0 and selfindex = 0
if psk_bone.parent_index == 0 and psk_bone.bone_index == psk_bone.parent_index:
if bDontInvertRoot:
psk_bone.mat_world_rot = psk_bone.orig_quat.to_matrix()
else:
psk_bone.mat_world_rot = psk_bone.orig_quat.conjugated().to_matrix()
psk_bone.mat_world = Matrix.Translation(psk_bone.orig_loc)
sum_bone_pos += psk_bone.orig_loc.length
#==================================================================================================
# Bones. Calc World-space matrix
# TODO optimize math.
for psk_bone in psk_bones:
if psk_bone.parent_index == 0:
if psk_bone.bone_index == 0:
psk_bone.parent = None
continue
parent = psk_bones[psk_bone.parent_index]
psk_bone.parent = parent
parent.children.append(psk_bone)
# mat_world - world space bone matrix WITHOUT own rotation
# mat_world_rot - world space bone rotation WITH own rotation
psk_bone.mat_world = parent.mat_world_rot.to_4x4()
psk_bone.mat_world.translation = parent.mat_world.translation + parent.mat_world_rot * psk_bone.orig_loc
psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()
# psk_bone.mat_world = ( parent.mat_world_rot.to_4x4() * psk_bone.trans)
# psk_bone.mat_world.translation += parent.mat_world.translation
# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()
#==================================================================================================
# Skeleton. Prepare.
armature_data = bpy.data.armatures.new(gen_names['armature_data'])
armature_obj = bpy.data.objects.new(gen_names['armature_object'], armature_data)
# TODO: options for axes and x_ray?
armature_data.show_axes = False
armature_data.draw_type = 'STICK'
armature_obj.show_x_ray = True
util_obj_link(context, armature_obj)
util_select_all(False)
util_obj_select(context, armature_obj)
util_obj_set_active(context, armature_obj)
utils_set_mode('EDIT')
sum_bone_pos /= len(Bones) # average
sum_bone_pos *= fBonesizeRatio # corrected
bone_size_choosen = max(0.01, round((min(sum_bone_pos, fBonesize))))
if not bReorientBones:
new_bone_size = bone_size_choosen
#==================================================================================================
# Skeleton. Build.
if psk_bone_name_toolong:
for psk_bone in psk_bones:
# TODO too long name cutting options?
long_name = psk_bone.name
psk_bone.name = psk_bone.name[-60:]
edit_bone = armature_obj.data.edit_bones.new(psk_bone.name)
edit_bone["long_name"] = long_name
psk_bone.name = edit_bone.name
# print(psk_bone.name)
# print(edit_bone.name)
else:
for psk_bone in psk_bones:
edit_bone = armature_obj.data.edit_bones.new(psk_bone.name)
psk_bone.name = edit_bone.name
for psk_bone in psk_bones:
edit_bone = armature_obj.data.edit_bones[psk_bone.name]
armature_obj.data.edit_bones.active = edit_bone
if psk_bone.parent is not None:
edit_bone.parent = armature_obj.data.edit_bones[psk_bone.parent.name]
else:
if bDontInvertRoot:
psk_bone.orig_quat.conjugate()
if bReorientBones:
(new_bone_size, quat_orient_diff) = calc_bone_rotation(psk_bone, bone_size_choosen, bReorientDirectly, sum_bone_pos)
post_quat = psk_bone.orig_quat.conjugated() * quat_orient_diff
else:
post_quat = psk_bone.orig_quat.conjugated()
# only length of this vector is matter?
edit_bone.tail = Vector(( 0.0, new_bone_size, 0.0))
# edit_bone.tail = Vector((0.0, 0.0, new_bone_size))
# edit_bone.matrix = psk_bone.mat_world * quat_diff.to_matrix().to_4x4()
edit_bone.matrix = psk_bone.mat_world * post_quat.to_matrix().to_4x4()
# some dev code...
#### FINAL
# post_quat = psk_bone.orig_quat.conjugated() * quat_diff
# edit_bone.matrix = psk_bone.mat_world * test_quat.to_matrix().to_4x4()
# edit_bone["post_quat"] = test_quat
####
# edit_bone["post_quat"] = Quaternion((1,0,0,0))
# edit_bone.matrix = psk_bone.mat_world* psk_bone.rot
# if edit_bone.parent:
# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (psk_bone.orig_quat.conjugated().to_matrix().to_4x4())
# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (test_quat.to_matrix().to_4x4())
# else:
# edit_bone.matrix = psk_bone.orig_quat.to_matrix().to_4x4()
# save bindPose information for .psa import
edit_bone["orig_quat"] = psk_bone.orig_quat
edit_bone["orig_loc"] = psk_bone.orig_loc
edit_bone["post_quat"] = post_quat
utils_set_mode('OBJECT')
#==================================================================================================
# Weights
if bImportmesh:
vertices_total = len(Vertices)
for ( _, PointIndex, BoneIndex ) in Weights:
if PointIndex < vertices_total: # can it be not?
psk_bones[BoneIndex].have_weight_data = True
# else:
# print(psk_bones[BoneIndex].name, 'for other mesh',PointIndex ,vertices_total)
#print("weight:", PointIndex, BoneIndex, Weight)
# Weights.append(None)
# print(Weights.count(None))
# Original vertex colorization code
'''
# Weights.sort( key = lambda wgh: wgh[0])
if bImportmesh:
VtxCol = []
bones_count = len(psk_bones)
for x in range(bones_count):
#change the overall darkness of each material in a range between 0.1 and 0.9
tmpVal = ((float(x) + 1.0) / bones_count * 0.7) + 0.1
tmpVal = int(tmpVal * 256)
tmpCol = [tmpVal, tmpVal, tmpVal, 0]
#Change the color of each material slightly
if x % 3 == 0:
if tmpCol[0] < 128:
tmpCol[0] += 60
else:
tmpCol[0] -= 60
if x % 3 == 1:
if tmpCol[1] < 128:
tmpCol[1] += 60
else:
tmpCol[1] -= 60
if x % 3 == 2:
if tmpCol[2] < 128:
tmpCol[2] += 60
else:
tmpCol[2] -= 60
#Add the material to the mesh
VtxCol.append(tmpCol)
for x in range(len(Tmsh.faces)):
for y in range(len(Tmsh.faces[x].v)):
#find v in Weights[n][0]
findVal = Tmsh.faces[x].v[y].index
n = 0
while findVal != Weights[n][0]:
n = n + 1
TmpCol = VtxCol[Weights[n][1]]
#check if a vertex has more than one influence
if n != len(Weights) - 1:
if Weights[n][0] == Weights[n + 1][0]:
#if there is more than one influence, use the one with the greater influence
#for simplicity only 2 influences are checked, 2nd and 3rd influences are usually very small
if Weights[n][2] < Weights[n + 1][2]:
TmpCol = VtxCol[Weights[n + 1][1]]
Tmsh.faces[x].col.append(NMesh.Col(TmpCol[0], TmpCol[1], TmpCol[2], 0))
'''
#===================================================================================================
# UV. Setup.
if bImportmesh:
# Trick! Create UV maps BEFORE mesh and get (0,0) coordinates for free!
# ...otherwise UV coords will be copied from active, or calculated from mesh...
if bSpltiUVdata:
for i in range(len(uv_mat_ids)):
get_uv_layers(mesh_data).new(name = NAME_UV_PREFIX + str(i))
else:
get_uv_layers(mesh_data).new(name = NAME_UV_PREFIX+"_SINGLE")
for counter, uv_data in enumerate(Extrauvs):
if len(mesh_data.uv_layers) < MAX_UVS:
get_uv_layers(mesh_data).new(name = "EXTRAUVS"+str(counter))
else:
Extrauvs.remove(uv_data)
print('Extra UV layer %s is ignored. Re-import without "Split UV data".' % counter)
#==================================================================================================
# Mesh. Build.
mesh_data.from_pydata(Vertices,[],Faces)
#==================================================================================================
# Vertex Normal. Set.
if Normals is not None:
mesh_data.polygons.foreach_set("use_smooth", [True] * len(mesh_data.polygons))
mesh_data.normals_split_custom_set_from_vertices(Normals)
mesh_data.use_auto_smooth = True
#===================================================================================================
# UV. Set.
if bImportmesh:
for face in mesh_data.polygons:
face.material_index = UV_by_face[face.index][1]
uv_layers = mesh_data.uv_layers
if not bSpltiUVdata:
uvLayer = uv_layers[0]
# per face
# for faceIdx, (faceUVs, faceMatIdx, _, _, wmidx) in enumerate(UV_by_face):
for faceIdx, (faceUVs, faceMatIdx, WedgeMatIds) in enumerate(UV_by_face):
# per vertex
for vertN, uv in enumerate(faceUVs):
loopId = faceIdx * 3 + vertN
if bSpltiUVdata:
uvLayer = uv_layers[WedgeMatIds[vertN]]
uvLayer.data[loopId].uv = uv
#===================================================================================================
# Extra UVs. Set.
for counter, uv_data in enumerate(Extrauvs):
uvLayer = mesh_data.uv_layers[ counter - len(Extrauvs) ]
for uv_index, uv_coords in enumerate(uv_data):
uvLayer.data[uv_index].uv = (uv_coords[0], 1.0 - uv_coords[1])
#===================================================================================================
# Mesh. Vertex Groups. Bone Weights.
for psk_bone in psk_bones:
if psk_bone.have_weight_data:
psk_bone.vertex_group = mesh_obj.vertex_groups.new(psk_bone.name)
# else:
# print(psk_bone.name, 'have no influence on this mesh')
for weight, vertex_id, bone_index_w in filter(None, Weights):
psk_bones[bone_index_w].vertex_group.add((vertex_id,), weight, 'ADD')
#===================================================================================================
# Skeleton. Colorize.
if bImportbone:
bone_group_unused = armature_obj.pose.bone_groups.new("Unused bones")
bone_group_unused.color_set = 'THEME14'
bone_group_nochild = armature_obj.pose.bone_groups.new("No children")
bone_group_nochild.color_set = 'THEME03'
armature_data.show_group_colors = True
for psk_bone in psk_bones:
pose_bone = armature_obj.pose.bones[psk_bone.name]
if psk_bone.have_weight_data:
if len(psk_bone.children) == 0:
pose_bone.bone_group = bone_group_nochild
else:
pose_bone.bone_group = bone_group_unused
#===================================================================================================
# Final
if bImportmesh:
util_obj_link(context, mesh_obj)
util_select_all(False)
if not bImportbone:
util_obj_select(context, mesh_obj)
util_obj_set_active(context, mesh_obj)
else:
# select_all(False)
util_obj_select(context, armature_obj)
# parenting mesh to armature object
mesh_obj.parent = armature_obj
mesh_obj.parent_type = 'OBJECT'
# add armature modifier
blender_modifier = mesh_obj.modifiers.new( armature_obj.data.name, type = 'ARMATURE')
blender_modifier.show_expanded = False
blender_modifier.use_vertex_groups = True
blender_modifier.use_bone_envelopes = False
blender_modifier.object = armature_obj
# utils_set_mode('OBJECT')
# select_all(False)
util_obj_select(context, armature_obj)
util_obj_set_active(context, armature_obj)
# print("Done: %f sec." % (time.process_time() - ref_time))
utils_set_mode('OBJECT')
return True | [
"def",
"pskimport",
"(",
"filepath",
",",
"context",
"=",
"bpy",
".",
"context",
",",
"bImportmesh",
"=",
"True",
",",
"bImportbone",
"=",
"True",
",",
"bSpltiUVdata",
"=",
"False",
",",
"fBonesize",
"=",
"5.0",
",",
"fBonesizeRatio",
"=",
"0.6",
",",
"bDontInvertRoot",
"=",
"False",
",",
"bReorientBones",
"=",
"False",
",",
"bReorientDirectly",
"=",
"False",
",",
"error_callback",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"error_callback",
",",
"'__call__'",
")",
":",
"error_callback",
"=",
"__pass",
"# ref_time = time.process_time()",
"if",
"not",
"bImportbone",
"and",
"not",
"bImportmesh",
":",
"error_callback",
"(",
"\"Nothing to do.\\nSet something for import.\"",
")",
"return",
"False",
"file_ext",
"=",
"'psk'",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"print",
"(",
"\"---------EXECUTING PSK PYTHON IMPORTER---------\"",
")",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"#file may not exist",
"try",
":",
"file",
"=",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"except",
"IOError",
":",
"error_callback",
"(",
"'Error while opening file for reading:\\n \"'",
"+",
"filepath",
"+",
"'\"'",
")",
"return",
"False",
"if",
"not",
"util_check_file_header",
"(",
"file",
",",
"'psk'",
")",
":",
"error_callback",
"(",
"'Not psk file:\\n \"'",
"+",
"filepath",
"+",
"'\"'",
")",
"return",
"False",
"Vertices",
"=",
"None",
"Wedges",
"=",
"None",
"Faces",
"=",
"None",
"UV_by_face",
"=",
"None",
"Materials",
"=",
"None",
"Bones",
"=",
"None",
"Weights",
"=",
"None",
"Extrauvs",
"=",
"[",
"]",
"Normals",
"=",
"None",
"#================================================================================================== ",
"# Materials MaterialNameRaw | TextureIndex | PolyFlags | AuxMaterial | AuxFlags | LodBias | LodStyle ",
"# Only Name is usable.",
"def",
"read_materials",
"(",
")",
":",
"nonlocal",
"Materials",
"Materials",
"=",
"[",
"]",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"MaterialNameRaw",
",",
")",
"=",
"unpack_from",
"(",
"'64s24x'",
",",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"Materials",
".",
"append",
"(",
"util_bytes_to_str",
"(",
"MaterialNameRaw",
")",
")",
"#================================================================================================== ",
"# Faces WdgIdx1 | WdgIdx2 | WdgIdx3 | MatIdx | AuxMatIdx | SmthGrp",
"def",
"read_faces",
"(",
")",
":",
"nonlocal",
"Faces",
",",
"UV_by_face",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"UV_by_face",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"Faces",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"if",
"len",
"(",
"Wedges",
")",
">",
"65536",
":",
"unpack_format",
"=",
"'=IIIBBI'",
"else",
":",
"unpack_format",
"=",
"'=HHHBBI'",
"unpack_data",
"=",
"Struct",
"(",
"unpack_format",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"WdgIdx1",
",",
"WdgIdx2",
",",
"WdgIdx3",
",",
"MatIndex",
",",
"AuxMatIndex",
",",
"#unused",
"SmoothingGroup",
"# Umodel is not exporting SmoothingGroups",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"# looks ugly",
"# Wedges is (point_index, u, v, MatIdx)",
"(",
"(",
"vertid0",
",",
"u0",
",",
"v0",
",",
"matid0",
")",
",",
"(",
"vertid1",
",",
"u1",
",",
"v1",
",",
"matid1",
")",
",",
"(",
"vertid2",
",",
"u2",
",",
"v2",
",",
"matid2",
")",
")",
"=",
"Wedges",
"[",
"WdgIdx1",
"]",
",",
"Wedges",
"[",
"WdgIdx2",
"]",
",",
"Wedges",
"[",
"WdgIdx3",
"]",
"# note order: C,B,A",
"Faces",
"[",
"counter",
"]",
"=",
"(",
"vertid2",
",",
"vertid1",
",",
"vertid0",
")",
"uv",
"=",
"(",
"(",
"u2",
",",
"1.0",
"-",
"v2",
")",
",",
"(",
"u1",
",",
"1.0",
"-",
"v1",
")",
",",
"(",
"u0",
",",
"1.0",
"-",
"v0",
")",
")",
"# Mapping: FaceIndex <=> UV data <=> FaceMatIndex",
"UV_by_face",
"[",
"counter",
"]",
"=",
"(",
"uv",
",",
"MatIndex",
",",
"(",
"matid2",
",",
"matid1",
",",
"matid0",
")",
")",
"#==================================================================================================",
"# Vertices X | Y | Z",
"def",
"read_vertices",
"(",
")",
":",
"nonlocal",
"bImportbone",
",",
"bImportmesh",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"nonlocal",
"Vertices",
"Vertices",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'3f'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"vec_x",
",",
"vec_y",
",",
"vec_z",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"Vertices",
"[",
"counter",
"]",
"=",
"(",
"vec_x",
",",
"vec_y",
",",
"vec_z",
")",
"#================================================================================================== ",
"# Wedges (UV) VertexId | U | V | MatIdx ",
"def",
"read_wedges",
"(",
")",
":",
"nonlocal",
"bImportbone",
",",
"bImportmesh",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"nonlocal",
"Wedges",
"Wedges",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'=IffBxxx'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"vertex_id",
",",
"u",
",",
"v",
",",
"material_index",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"# print(vertex_id, u, v, material_index)",
"# Wedges[counter] = (vertex_id, u, v, material_index)",
"Wedges",
"[",
"counter",
"]",
"=",
"[",
"vertex_id",
",",
"u",
",",
"v",
",",
"material_index",
"]",
"#================================================================================================== ",
"# Bones (VBone .. VJointPos ) Name|Flgs|NumChld|PrntIdx|Qw|Qx|Qy|Qz|LocX|LocY|LocZ|Lngth|XSize|YSize|ZSize",
"def",
"read_bones",
"(",
")",
":",
"nonlocal",
"Bones",
",",
"bImportbone",
"if",
"chunk_datacount",
"==",
"0",
":",
"bImportbone",
"=",
"False",
"if",
"bImportbone",
":",
"unpack_data",
"=",
"Struct",
"(",
"'64s3i11f'",
")",
".",
"unpack_from",
"else",
":",
"unpack_data",
"=",
"Struct",
"(",
"'64s56x'",
")",
".",
"unpack_from",
"Bones",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"Bones",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"#================================================================================================== ",
"# Influences (Bone Weight) (VRawBoneInfluence) ( Weight | PntIdx | BoneIdx)",
"def",
"read_weights",
"(",
")",
":",
"# nonlocal Weights, bImportmesh",
"nonlocal",
"Weights",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"Weights",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'fii'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"Weights",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"#================================================================================================== ",
"# Extra UV. U | V",
"def",
"read_extrauvs",
"(",
")",
":",
"unpack_data",
"=",
"Struct",
"(",
"\"=2f\"",
")",
".",
"unpack_from",
"uvdata",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"uvdata",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"Extrauvs",
".",
"append",
"(",
"uvdata",
")",
"#==================================================================================================",
"# Vertex Normals NX | NY | NZ",
"def",
"read_normals",
"(",
")",
":",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"nonlocal",
"Normals",
"Normals",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'3f'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"Normals",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"CHUNKS_HANDLERS",
"=",
"{",
"'PNTS0000'",
":",
"read_vertices",
",",
"'VTXW0000'",
":",
"read_wedges",
",",
"'VTXW3200'",
":",
"read_wedges",
",",
"#?",
"'FACE0000'",
":",
"read_faces",
",",
"'FACE3200'",
":",
"read_faces",
",",
"'MATT0000'",
":",
"read_materials",
",",
"'REFSKELT'",
":",
"read_bones",
",",
"'REFSKEL0'",
":",
"read_bones",
",",
"#?",
"'RAWW0000'",
":",
"read_weights",
",",
"'RAWWEIGH'",
":",
"read_weights",
",",
"'EXTRAUVS'",
":",
"read_extrauvs",
",",
"'VTXNORMS'",
":",
"read_normals",
"}",
"#===================================================================================================",
"# File. Read all needed data.",
"# VChunkHeader Struct",
"# ChunkID|TypeFlag|DataSize|DataCount",
"# 0 |1 |2 |3",
"while",
"True",
":",
"header_bytes",
"=",
"file",
".",
"read",
"(",
"32",
")",
"if",
"len",
"(",
"header_bytes",
")",
"<",
"32",
":",
"if",
"len",
"(",
"header_bytes",
")",
"!=",
"0",
":",
"error_callback",
"(",
"\"Unexpected end of file.(%s/32 bytes)\"",
"%",
"len",
"(",
"header_bytes",
")",
")",
"break",
"(",
"chunk_id",
",",
"chunk_type",
",",
"chunk_datasize",
",",
"chunk_datacount",
")",
"=",
"unpack",
"(",
"'20s3i'",
",",
"header_bytes",
")",
"chunk_id_str",
"=",
"util_bytes_to_str",
"(",
"chunk_id",
")",
"chunk_id_str",
"=",
"chunk_id_str",
"[",
":",
"8",
"]",
"if",
"chunk_id_str",
"in",
"CHUNKS_HANDLERS",
":",
"chunk_data",
"=",
"file",
".",
"read",
"(",
"chunk_datasize",
"*",
"chunk_datacount",
")",
"if",
"len",
"(",
"chunk_data",
")",
"<",
"chunk_datasize",
"*",
"chunk_datacount",
":",
"error_callback",
"(",
"'Psk chunk %s is broken.'",
"%",
"chunk_id_str",
")",
"return",
"False",
"CHUNKS_HANDLERS",
"[",
"chunk_id_str",
"]",
"(",
")",
"else",
":",
"print",
"(",
"'Unknown chunk: '",
",",
"chunk_id_str",
")",
"file",
".",
"seek",
"(",
"chunk_datasize",
"*",
"chunk_datacount",
",",
"1",
")",
"# print(chunk_id_str, chunk_datacount)",
"file",
".",
"close",
"(",
")",
"print",
"(",
"\" Importing file:\"",
",",
"filepath",
")",
"if",
"not",
"bImportmesh",
"and",
"(",
"Bones",
"is",
"None",
"or",
"len",
"(",
"Bones",
")",
"==",
"0",
")",
":",
"error_callback",
"(",
"\"Psk: no skeleton data.\"",
")",
"return",
"False",
"MAX_UVS",
"=",
"8",
"NAME_UV_PREFIX",
"=",
"\"UV\"",
"# file name w/out extension",
"gen_name_part",
"=",
"util_gen_name_part",
"(",
"filepath",
")",
"gen_names",
"=",
"{",
"'armature_object'",
":",
"gen_name_part",
"+",
"'.ao'",
",",
"'armature_data'",
":",
"gen_name_part",
"+",
"'.ad'",
",",
"'mesh_object'",
":",
"gen_name_part",
"+",
"'.mo'",
",",
"'mesh_data'",
":",
"gen_name_part",
"+",
"'.md'",
"}",
"if",
"bImportmesh",
":",
"mesh_data",
"=",
"bpy",
".",
"data",
".",
"meshes",
".",
"new",
"(",
"gen_names",
"[",
"'mesh_data'",
"]",
")",
"mesh_obj",
"=",
"bpy",
".",
"data",
".",
"objects",
".",
"new",
"(",
"gen_names",
"[",
"'mesh_object'",
"]",
",",
"mesh_data",
")",
"#==================================================================================================",
"# UV. Prepare",
"if",
"bImportmesh",
":",
"if",
"bSpltiUVdata",
":",
"# store how much each \"matrial index\" have vertices",
"uv_mat_ids",
"=",
"{",
"}",
"for",
"(",
"_",
",",
"_",
",",
"_",
",",
"material_index",
")",
"in",
"Wedges",
":",
"if",
"not",
"(",
"material_index",
"in",
"uv_mat_ids",
")",
":",
"uv_mat_ids",
"[",
"material_index",
"]",
"=",
"1",
"else",
":",
"uv_mat_ids",
"[",
"material_index",
"]",
"+=",
"1",
"# if we have more UV material indexes than blender UV maps, then...",
"if",
"bSpltiUVdata",
"and",
"len",
"(",
"uv_mat_ids",
")",
">",
"MAX_UVS",
":",
"uv_mat_ids_len",
"=",
"len",
"(",
"uv_mat_ids",
")",
"print",
"(",
"'UVs: %s out of %s is combined in a first UV map(%s0)'",
"%",
"(",
"uv_mat_ids_len",
"-",
"8",
",",
"uv_mat_ids_len",
",",
"NAME_UV_PREFIX",
")",
")",
"mat_idx_proxy",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"uv_mat_ids",
")",
"counts_sorted",
"=",
"sorted",
"(",
"uv_mat_ids",
".",
"values",
"(",
")",
",",
"reverse",
"=",
"True",
")",
"new_mat_index",
"=",
"MAX_UVS",
"-",
"1",
"for",
"c",
"in",
"counts_sorted",
":",
"for",
"mat_idx",
",",
"counts",
"in",
"uv_mat_ids",
".",
"items",
"(",
")",
":",
"if",
"c",
"==",
"counts",
":",
"mat_idx_proxy",
"[",
"mat_idx",
"]",
"=",
"new_mat_index",
"if",
"new_mat_index",
">",
"0",
":",
"new_mat_index",
"-=",
"1",
"# print('MatIdx remap: %s > %s' % (mat_idx,new_mat_index))",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"Wedges",
")",
")",
":",
"Wedges",
"[",
"i",
"]",
"[",
"3",
"]",
"=",
"mat_idx_proxy",
"[",
"Wedges",
"[",
"i",
"]",
"[",
"3",
"]",
"]",
"# print('Wedges:', chunk_datacount)",
"# print('uv_mat_ids', uv_mat_ids)",
"# print('uv_mat_ids', uv_mat_ids)",
"# for w in Wedges:",
"if",
"bImportmesh",
":",
"# print(\"-- Materials -- (index, name, faces)\")",
"blen_materials",
"=",
"[",
"]",
"for",
"materialname",
"in",
"Materials",
":",
"matdata",
"=",
"bpy",
".",
"data",
".",
"materials",
".",
"get",
"(",
"materialname",
")",
"if",
"matdata",
"is",
"None",
":",
"matdata",
"=",
"bpy",
".",
"data",
".",
"materials",
".",
"new",
"(",
"materialname",
")",
"# matdata = bpy.data.materials.new( materialname )",
"blen_materials",
".",
"append",
"(",
"matdata",
")",
"mesh_data",
".",
"materials",
".",
"append",
"(",
"matdata",
")",
"# print(counter,materialname,TextureIndex)",
"# if mat_groups.get(counter) is not None:",
"# print(\"%i: %s\" % (counter, materialname), len(mat_groups[counter]))",
"#==================================================================================================",
"# Prepare bone data",
"psk_bone_name_toolong",
"=",
"False",
"def",
"init_psk_bone",
"(",
"i",
",",
"psk_bones",
",",
"name_raw",
")",
":",
"psk_bone",
"=",
"class_psk_bone",
"(",
")",
"psk_bone",
".",
"children",
"=",
"[",
"]",
"psk_bone",
".",
"name",
"=",
"util_bytes_to_str",
"(",
"name_raw",
")",
"psk_bones",
"[",
"i",
"]",
"=",
"psk_bone",
"return",
"psk_bone",
"# indexed by bone index. array of psk_bone",
"psk_bones",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"Bones",
")",
"if",
"not",
"bImportbone",
":",
"#data needed for mesh-only import",
"for",
"counter",
",",
"(",
"name_raw",
",",
")",
"in",
"enumerate",
"(",
"Bones",
")",
":",
"init_psk_bone",
"(",
"counter",
",",
"psk_bones",
",",
"name_raw",
")",
"if",
"bImportbone",
":",
"#else?",
"# average bone length",
"sum_bone_pos",
"=",
"0",
"for",
"counter",
",",
"(",
"name_raw",
",",
"flags",
",",
"NumChildren",
",",
"ParentIndex",
",",
"#0 1 2 3",
"quat_x",
",",
"quat_y",
",",
"quat_z",
",",
"quat_w",
",",
"#4 5 6 7",
"vec_x",
",",
"vec_y",
",",
"vec_z",
",",
"#8 9 10",
"joint_length",
",",
"#11",
"scale_x",
",",
"scale_y",
",",
"scale_z",
")",
"in",
"enumerate",
"(",
"Bones",
")",
":",
"psk_bone",
"=",
"init_psk_bone",
"(",
"counter",
",",
"psk_bones",
",",
"name_raw",
")",
"psk_bone",
".",
"bone_index",
"=",
"counter",
"psk_bone",
".",
"parent_index",
"=",
"ParentIndex",
"if",
"len",
"(",
"psk_bone",
".",
"name",
")",
">",
"60",
":",
"psk_bone_name_toolong",
"=",
"True",
"# print(psk_bone.bone_index, psk_bone.parent_index, psk_bone.name) ",
"# make sure we have valid parent_index",
"if",
"psk_bone",
".",
"parent_index",
"<",
"0",
":",
"psk_bone",
".",
"parent_index",
"=",
"0",
"# psk_bone.scale = (scale_x, scale_y, scale_z)",
"# store bind pose to make it available for psa-import via CustomProperty of the Blender bone",
"psk_bone",
".",
"orig_quat",
"=",
"Quaternion",
"(",
"(",
"quat_w",
",",
"quat_x",
",",
"quat_y",
",",
"quat_z",
")",
")",
"psk_bone",
".",
"orig_loc",
"=",
"Vector",
"(",
"(",
"vec_x",
",",
"vec_y",
",",
"vec_z",
")",
")",
"# root bone must have parent_index = 0 and selfindex = 0",
"if",
"psk_bone",
".",
"parent_index",
"==",
"0",
"and",
"psk_bone",
".",
"bone_index",
"==",
"psk_bone",
".",
"parent_index",
":",
"if",
"bDontInvertRoot",
":",
"psk_bone",
".",
"mat_world_rot",
"=",
"psk_bone",
".",
"orig_quat",
".",
"to_matrix",
"(",
")",
"else",
":",
"psk_bone",
".",
"mat_world_rot",
"=",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
".",
"to_matrix",
"(",
")",
"psk_bone",
".",
"mat_world",
"=",
"Matrix",
".",
"Translation",
"(",
"psk_bone",
".",
"orig_loc",
")",
"sum_bone_pos",
"+=",
"psk_bone",
".",
"orig_loc",
".",
"length",
"#==================================================================================================",
"# Bones. Calc World-space matrix",
"# TODO optimize math.",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"if",
"psk_bone",
".",
"parent_index",
"==",
"0",
":",
"if",
"psk_bone",
".",
"bone_index",
"==",
"0",
":",
"psk_bone",
".",
"parent",
"=",
"None",
"continue",
"parent",
"=",
"psk_bones",
"[",
"psk_bone",
".",
"parent_index",
"]",
"psk_bone",
".",
"parent",
"=",
"parent",
"parent",
".",
"children",
".",
"append",
"(",
"psk_bone",
")",
"# mat_world - world space bone matrix WITHOUT own rotation",
"# mat_world_rot - world space bone rotation WITH own rotation",
"psk_bone",
".",
"mat_world",
"=",
"parent",
".",
"mat_world_rot",
".",
"to_4x4",
"(",
")",
"psk_bone",
".",
"mat_world",
".",
"translation",
"=",
"parent",
".",
"mat_world",
".",
"translation",
"+",
"parent",
".",
"mat_world_rot",
"*",
"psk_bone",
".",
"orig_loc",
"psk_bone",
".",
"mat_world_rot",
"=",
"parent",
".",
"mat_world_rot",
"*",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
".",
"to_matrix",
"(",
")",
"# psk_bone.mat_world = ( parent.mat_world_rot.to_4x4() * psk_bone.trans)",
"# psk_bone.mat_world.translation += parent.mat_world.translation",
"# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()",
"#==================================================================================================",
"# Skeleton. Prepare.",
"armature_data",
"=",
"bpy",
".",
"data",
".",
"armatures",
".",
"new",
"(",
"gen_names",
"[",
"'armature_data'",
"]",
")",
"armature_obj",
"=",
"bpy",
".",
"data",
".",
"objects",
".",
"new",
"(",
"gen_names",
"[",
"'armature_object'",
"]",
",",
"armature_data",
")",
"# TODO: options for axes and x_ray?",
"armature_data",
".",
"show_axes",
"=",
"False",
"armature_data",
".",
"draw_type",
"=",
"'STICK'",
"armature_obj",
".",
"show_x_ray",
"=",
"True",
"util_obj_link",
"(",
"context",
",",
"armature_obj",
")",
"util_select_all",
"(",
"False",
")",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")",
"utils_set_mode",
"(",
"'EDIT'",
")",
"sum_bone_pos",
"/=",
"len",
"(",
"Bones",
")",
"# average",
"sum_bone_pos",
"*=",
"fBonesizeRatio",
"# corrected",
"bone_size_choosen",
"=",
"max",
"(",
"0.01",
",",
"round",
"(",
"(",
"min",
"(",
"sum_bone_pos",
",",
"fBonesize",
")",
")",
")",
")",
"if",
"not",
"bReorientBones",
":",
"new_bone_size",
"=",
"bone_size_choosen",
"#==================================================================================================",
"# Skeleton. Build.",
"if",
"psk_bone_name_toolong",
":",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"# TODO too long name cutting options?",
"long_name",
"=",
"psk_bone",
".",
"name",
"psk_bone",
".",
"name",
"=",
"psk_bone",
".",
"name",
"[",
"-",
"60",
":",
"]",
"edit_bone",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
".",
"new",
"(",
"psk_bone",
".",
"name",
")",
"edit_bone",
"[",
"\"long_name\"",
"]",
"=",
"long_name",
"psk_bone",
".",
"name",
"=",
"edit_bone",
".",
"name",
"# print(psk_bone.name)",
"# print(edit_bone.name)",
"else",
":",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"edit_bone",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
".",
"new",
"(",
"psk_bone",
".",
"name",
")",
"psk_bone",
".",
"name",
"=",
"edit_bone",
".",
"name",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"edit_bone",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
"[",
"psk_bone",
".",
"name",
"]",
"armature_obj",
".",
"data",
".",
"edit_bones",
".",
"active",
"=",
"edit_bone",
"if",
"psk_bone",
".",
"parent",
"is",
"not",
"None",
":",
"edit_bone",
".",
"parent",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
"[",
"psk_bone",
".",
"parent",
".",
"name",
"]",
"else",
":",
"if",
"bDontInvertRoot",
":",
"psk_bone",
".",
"orig_quat",
".",
"conjugate",
"(",
")",
"if",
"bReorientBones",
":",
"(",
"new_bone_size",
",",
"quat_orient_diff",
")",
"=",
"calc_bone_rotation",
"(",
"psk_bone",
",",
"bone_size_choosen",
",",
"bReorientDirectly",
",",
"sum_bone_pos",
")",
"post_quat",
"=",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
"*",
"quat_orient_diff",
"else",
":",
"post_quat",
"=",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
"# only length of this vector is matter?",
"edit_bone",
".",
"tail",
"=",
"Vector",
"(",
"(",
"0.0",
",",
"new_bone_size",
",",
"0.0",
")",
")",
"# edit_bone.tail = Vector((0.0, 0.0, new_bone_size))",
"# edit_bone.matrix = psk_bone.mat_world * quat_diff.to_matrix().to_4x4()",
"edit_bone",
".",
"matrix",
"=",
"psk_bone",
".",
"mat_world",
"*",
"post_quat",
".",
"to_matrix",
"(",
")",
".",
"to_4x4",
"(",
")",
"# some dev code...",
"#### FINAL",
"# post_quat = psk_bone.orig_quat.conjugated() * quat_diff",
"# edit_bone.matrix = psk_bone.mat_world * test_quat.to_matrix().to_4x4()",
"# edit_bone[\"post_quat\"] = test_quat",
"#### ",
"# edit_bone[\"post_quat\"] = Quaternion((1,0,0,0))",
"# edit_bone.matrix = psk_bone.mat_world* psk_bone.rot",
"# if edit_bone.parent:",
"# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (psk_bone.orig_quat.conjugated().to_matrix().to_4x4())",
"# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (test_quat.to_matrix().to_4x4())",
"# else:",
"# edit_bone.matrix = psk_bone.orig_quat.to_matrix().to_4x4()",
"# save bindPose information for .psa import",
"edit_bone",
"[",
"\"orig_quat\"",
"]",
"=",
"psk_bone",
".",
"orig_quat",
"edit_bone",
"[",
"\"orig_loc\"",
"]",
"=",
"psk_bone",
".",
"orig_loc",
"edit_bone",
"[",
"\"post_quat\"",
"]",
"=",
"post_quat",
"utils_set_mode",
"(",
"'OBJECT'",
")",
"#==================================================================================================",
"# Weights",
"if",
"bImportmesh",
":",
"vertices_total",
"=",
"len",
"(",
"Vertices",
")",
"for",
"(",
"_",
",",
"PointIndex",
",",
"BoneIndex",
")",
"in",
"Weights",
":",
"if",
"PointIndex",
"<",
"vertices_total",
":",
"# can it be not?",
"psk_bones",
"[",
"BoneIndex",
"]",
".",
"have_weight_data",
"=",
"True",
"# else:",
"# print(psk_bones[BoneIndex].name, 'for other mesh',PointIndex ,vertices_total)",
"#print(\"weight:\", PointIndex, BoneIndex, Weight)",
"# Weights.append(None)",
"# print(Weights.count(None))",
"# Original vertex colorization code",
"'''\n # Weights.sort( key = lambda wgh: wgh[0])\n if bImportmesh:\n VtxCol = []\n bones_count = len(psk_bones)\n for x in range(bones_count):\n #change the overall darkness of each material in a range between 0.1 and 0.9\n tmpVal = ((float(x) + 1.0) / bones_count * 0.7) + 0.1\n tmpVal = int(tmpVal * 256)\n tmpCol = [tmpVal, tmpVal, tmpVal, 0]\n #Change the color of each material slightly\n if x % 3 == 0:\n if tmpCol[0] < 128:\n tmpCol[0] += 60\n else:\n tmpCol[0] -= 60\n if x % 3 == 1:\n if tmpCol[1] < 128:\n tmpCol[1] += 60\n else:\n tmpCol[1] -= 60\n if x % 3 == 2:\n if tmpCol[2] < 128:\n tmpCol[2] += 60\n else:\n tmpCol[2] -= 60\n #Add the material to the mesh\n VtxCol.append(tmpCol)\n \n for x in range(len(Tmsh.faces)):\n for y in range(len(Tmsh.faces[x].v)):\n #find v in Weights[n][0]\n findVal = Tmsh.faces[x].v[y].index\n n = 0\n while findVal != Weights[n][0]:\n n = n + 1\n TmpCol = VtxCol[Weights[n][1]]\n #check if a vertex has more than one influence\n if n != len(Weights) - 1:\n if Weights[n][0] == Weights[n + 1][0]:\n #if there is more than one influence, use the one with the greater influence\n #for simplicity only 2 influences are checked, 2nd and 3rd influences are usually very small\n if Weights[n][2] < Weights[n + 1][2]:\n TmpCol = VtxCol[Weights[n + 1][1]]\n Tmsh.faces[x].col.append(NMesh.Col(TmpCol[0], TmpCol[1], TmpCol[2], 0))\n '''",
"#===================================================================================================",
"# UV. Setup.",
"if",
"bImportmesh",
":",
"# Trick! Create UV maps BEFORE mesh and get (0,0) coordinates for free!",
"# ...otherwise UV coords will be copied from active, or calculated from mesh...",
"if",
"bSpltiUVdata",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"uv_mat_ids",
")",
")",
":",
"get_uv_layers",
"(",
"mesh_data",
")",
".",
"new",
"(",
"name",
"=",
"NAME_UV_PREFIX",
"+",
"str",
"(",
"i",
")",
")",
"else",
":",
"get_uv_layers",
"(",
"mesh_data",
")",
".",
"new",
"(",
"name",
"=",
"NAME_UV_PREFIX",
"+",
"\"_SINGLE\"",
")",
"for",
"counter",
",",
"uv_data",
"in",
"enumerate",
"(",
"Extrauvs",
")",
":",
"if",
"len",
"(",
"mesh_data",
".",
"uv_layers",
")",
"<",
"MAX_UVS",
":",
"get_uv_layers",
"(",
"mesh_data",
")",
".",
"new",
"(",
"name",
"=",
"\"EXTRAUVS\"",
"+",
"str",
"(",
"counter",
")",
")",
"else",
":",
"Extrauvs",
".",
"remove",
"(",
"uv_data",
")",
"print",
"(",
"'Extra UV layer %s is ignored. Re-import without \"Split UV data\".'",
"%",
"counter",
")",
"#================================================================================================== ",
"# Mesh. Build.",
"mesh_data",
".",
"from_pydata",
"(",
"Vertices",
",",
"[",
"]",
",",
"Faces",
")",
"#==================================================================================================",
"# Vertex Normal. Set.",
"if",
"Normals",
"is",
"not",
"None",
":",
"mesh_data",
".",
"polygons",
".",
"foreach_set",
"(",
"\"use_smooth\"",
",",
"[",
"True",
"]",
"*",
"len",
"(",
"mesh_data",
".",
"polygons",
")",
")",
"mesh_data",
".",
"normals_split_custom_set_from_vertices",
"(",
"Normals",
")",
"mesh_data",
".",
"use_auto_smooth",
"=",
"True",
"#===================================================================================================",
"# UV. Set.",
"if",
"bImportmesh",
":",
"for",
"face",
"in",
"mesh_data",
".",
"polygons",
":",
"face",
".",
"material_index",
"=",
"UV_by_face",
"[",
"face",
".",
"index",
"]",
"[",
"1",
"]",
"uv_layers",
"=",
"mesh_data",
".",
"uv_layers",
"if",
"not",
"bSpltiUVdata",
":",
"uvLayer",
"=",
"uv_layers",
"[",
"0",
"]",
"# per face",
"# for faceIdx, (faceUVs, faceMatIdx, _, _, wmidx) in enumerate(UV_by_face):",
"for",
"faceIdx",
",",
"(",
"faceUVs",
",",
"faceMatIdx",
",",
"WedgeMatIds",
")",
"in",
"enumerate",
"(",
"UV_by_face",
")",
":",
"# per vertex",
"for",
"vertN",
",",
"uv",
"in",
"enumerate",
"(",
"faceUVs",
")",
":",
"loopId",
"=",
"faceIdx",
"*",
"3",
"+",
"vertN",
"if",
"bSpltiUVdata",
":",
"uvLayer",
"=",
"uv_layers",
"[",
"WedgeMatIds",
"[",
"vertN",
"]",
"]",
"uvLayer",
".",
"data",
"[",
"loopId",
"]",
".",
"uv",
"=",
"uv",
"#===================================================================================================",
"# Extra UVs. Set.",
"for",
"counter",
",",
"uv_data",
"in",
"enumerate",
"(",
"Extrauvs",
")",
":",
"uvLayer",
"=",
"mesh_data",
".",
"uv_layers",
"[",
"counter",
"-",
"len",
"(",
"Extrauvs",
")",
"]",
"for",
"uv_index",
",",
"uv_coords",
"in",
"enumerate",
"(",
"uv_data",
")",
":",
"uvLayer",
".",
"data",
"[",
"uv_index",
"]",
".",
"uv",
"=",
"(",
"uv_coords",
"[",
"0",
"]",
",",
"1.0",
"-",
"uv_coords",
"[",
"1",
"]",
")",
"#===================================================================================================",
"# Mesh. Vertex Groups. Bone Weights.",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"if",
"psk_bone",
".",
"have_weight_data",
":",
"psk_bone",
".",
"vertex_group",
"=",
"mesh_obj",
".",
"vertex_groups",
".",
"new",
"(",
"psk_bone",
".",
"name",
")",
"# else:",
"# print(psk_bone.name, 'have no influence on this mesh')",
"for",
"weight",
",",
"vertex_id",
",",
"bone_index_w",
"in",
"filter",
"(",
"None",
",",
"Weights",
")",
":",
"psk_bones",
"[",
"bone_index_w",
"]",
".",
"vertex_group",
".",
"add",
"(",
"(",
"vertex_id",
",",
")",
",",
"weight",
",",
"'ADD'",
")",
"#===================================================================================================",
"# Skeleton. Colorize.",
"if",
"bImportbone",
":",
"bone_group_unused",
"=",
"armature_obj",
".",
"pose",
".",
"bone_groups",
".",
"new",
"(",
"\"Unused bones\"",
")",
"bone_group_unused",
".",
"color_set",
"=",
"'THEME14'",
"bone_group_nochild",
"=",
"armature_obj",
".",
"pose",
".",
"bone_groups",
".",
"new",
"(",
"\"No children\"",
")",
"bone_group_nochild",
".",
"color_set",
"=",
"'THEME03'",
"armature_data",
".",
"show_group_colors",
"=",
"True",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"pose_bone",
"=",
"armature_obj",
".",
"pose",
".",
"bones",
"[",
"psk_bone",
".",
"name",
"]",
"if",
"psk_bone",
".",
"have_weight_data",
":",
"if",
"len",
"(",
"psk_bone",
".",
"children",
")",
"==",
"0",
":",
"pose_bone",
".",
"bone_group",
"=",
"bone_group_nochild",
"else",
":",
"pose_bone",
".",
"bone_group",
"=",
"bone_group_unused",
"#===================================================================================================",
"# Final",
"if",
"bImportmesh",
":",
"util_obj_link",
"(",
"context",
",",
"mesh_obj",
")",
"util_select_all",
"(",
"False",
")",
"if",
"not",
"bImportbone",
":",
"util_obj_select",
"(",
"context",
",",
"mesh_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"mesh_obj",
")",
"else",
":",
"# select_all(False)",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"# parenting mesh to armature object",
"mesh_obj",
".",
"parent",
"=",
"armature_obj",
"mesh_obj",
".",
"parent_type",
"=",
"'OBJECT'",
"# add armature modifier",
"blender_modifier",
"=",
"mesh_obj",
".",
"modifiers",
".",
"new",
"(",
"armature_obj",
".",
"data",
".",
"name",
",",
"type",
"=",
"'ARMATURE'",
")",
"blender_modifier",
".",
"show_expanded",
"=",
"False",
"blender_modifier",
".",
"use_vertex_groups",
"=",
"True",
"blender_modifier",
".",
"use_bone_envelopes",
"=",
"False",
"blender_modifier",
".",
"object",
"=",
"armature_obj",
"# utils_set_mode('OBJECT')",
"# select_all(False)",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")",
"# print(\"Done: %f sec.\" % (time.process_time() - ref_time))",
"utils_set_mode",
"(",
"'OBJECT'",
")",
"return",
"True"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_270.py#L273-L1036 |
|
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_270.py | python | psaimport | (filepath,
context = bpy.context,
oArmature = None,
bFilenameAsPrefix = False,
bActionsToTrack = False,
first_frames = 0,
bDontInvertRoot = False,
bUpdateTimelineRange = False,
fcurve_interpolation = 'LINEAR',
error_callback = __pass
) | Import animation data from 'filepath' using 'oArmature'
Args:
first_frames: (0 - import all)
Import only 'first_frames' from each action
bActionsToTrack:
Put all imported actions in one NLAtrack.
oArmature:
Skeleton used to calculate keyframes | Import animation data from 'filepath' using 'oArmature'
Args:
first_frames: (0 - import all)
Import only 'first_frames' from each action
bActionsToTrack:
Put all imported actions in one NLAtrack.
oArmature:
Skeleton used to calculate keyframes | [
"Import",
"animation",
"data",
"from",
"filepath",
"using",
"oArmature",
"Args",
":",
"first_frames",
":",
"(",
"0",
"-",
"import",
"all",
")",
"Import",
"only",
"first_frames",
"from",
"each",
"action",
"bActionsToTrack",
":",
"Put",
"all",
"imported",
"actions",
"in",
"one",
"NLAtrack",
".",
"oArmature",
":",
"Skeleton",
"used",
"to",
"calculate",
"keyframes"
] | def psaimport(filepath,
context = bpy.context,
oArmature = None,
bFilenameAsPrefix = False,
bActionsToTrack = False,
first_frames = 0,
bDontInvertRoot = False,
bUpdateTimelineRange = False,
fcurve_interpolation = 'LINEAR',
error_callback = __pass
):
"""Import animation data from 'filepath' using 'oArmature'
Args:
first_frames: (0 - import all)
Import only 'first_frames' from each action
bActionsToTrack:
Put all imported actions in one NLAtrack.
oArmature:
Skeleton used to calculate keyframes
"""
print ("-----------------------------------------------")
print ("---------EXECUTING PSA PYTHON IMPORTER---------")
print ("-----------------------------------------------")
file_ext = 'psa'
try:
psafile = open(filepath, 'rb')
except IOError:
error_callback('Error while opening file for reading:\n "'+filepath+'"')
return False
print ("Importing file: ", filepath)
armature_obj = oArmature
if armature_obj is None:
armature_obj = blen_get_armature_from_selection()
if armature_obj is None:
error_callback("No armature selected.")
return False
chunk_id = None
chunk_type = None
chunk_datasize = None
chunk_datacount = None
chunk_data = None
def read_chunk():
nonlocal chunk_id, chunk_type,\
chunk_datasize, chunk_datacount,\
chunk_data
(chunk_id, chunk_type,
chunk_datasize, chunk_datacount) = unpack('20s3i', psafile.read(32))
chunk_data = psafile.read(chunk_datacount * chunk_datasize)
#==============================================================================================
# General Header
#==============================================================================================
read_chunk()
if not util_is_header_valid(filepath, file_ext, chunk_id, error_callback):
return False
#==============================================================================================
# Bones (FNamedBoneBinary)
#==============================================================================================
read_chunk()
psa_bones = {}
def new_psa_bone(bone, pose_bone):
psa_bone = class_psa_bone()
psa_bones[pose_bone.name] = psa_bone
psa_bone.name = pose_bone.name
psa_bone.pose_bone = pose_bone
if bone.parent != None:
# does needed parent bone was added from psa file
if bone.parent.name in psa_bones:
psa_bone.parent = psa_bones[bone.parent.name]
# no. armature doesnt match
else:
psa_bone.parent = None
# else:
# psa_bone.parent = None
psa_bone.orig_quat = Quaternion(bone['orig_quat'])
psa_bone.orig_loc = Vector(bone['orig_loc'])
psa_bone.post_quat = Quaternion(bone['post_quat'])
return psa_bone
#Bones Data
BoneIndex2Name = [None] * chunk_datacount
BoneNotFoundList = []
BonesWithoutAnimation = []
PsaBonesToProcess = [None] * chunk_datacount
# printlog("Name\tFlgs\tNumChld\tPrntIdx\tQx\tQy\tQz\tQw\tLocX\tLocY\tLocZ\tLength\tXSize\tYSize\tZSize\n")
# for case insensetive comparison
# key = lowered name
# value = orignal name
skeleton_bones_lowered = {}
for blender_bone_name in armature_obj.data.bones.keys():
skeleton_bones_lowered[blender_bone_name.lower()] = blender_bone_name
for counter in range(chunk_datacount):
# tPrntIdx is -1 for parent; and 0 for other; no more useful data
# indata = unpack_from('64s3i11f', chunk_data, chunk_datasize * counter)
(indata) = unpack_from('64s56x', chunk_data, chunk_datasize * counter)
in_name = util_bytes_to_str(indata[0])
# bonename = util_bytes_to_str(indata[0]).upper()
in_name_lowered = in_name.lower()
if in_name_lowered in skeleton_bones_lowered:
orig_name = skeleton_bones_lowered[in_name_lowered]
# use a skeleton bone name
BoneIndex2Name[counter] = orig_name
PsaBonesToProcess[counter] = new_psa_bone(armature_obj.data.bones[orig_name],
armature_obj.pose.bones[orig_name])
else:
# print("Can't find the bone:", bonename)
BoneNotFoundList.append(counter)
if len(psa_bones) == 0:
error_callback('No bone was match!\nSkip import!')
return False
# does anyone care?
for blender_bone_name in armature_obj.data.bones.keys():
if BoneIndex2Name.count(blender_bone_name) == 0:
BonesWithoutAnimation.append(blender_bone_name)
if len(BoneNotFoundList) > 0:
print('Not found bones: %i.' % len(BoneNotFoundList));
if len(BonesWithoutAnimation) > 0:
print('Bones(%i) without animation data:\n' % len(BonesWithoutAnimation), ', '.join(BonesWithoutAnimation))
#==============================================================================================
# Animations (AniminfoBinary)
#==============================================================================================
read_chunk()
Raw_Key_Nums = 0
Action_List = [None] * chunk_datacount
for counter in range(chunk_datacount):
(action_name_raw, #0
group_name_raw, #1
Totalbones, #2
RootInclude, #3
KeyCompressionStyle, #4
KeyQuotum, #5
KeyReduction, #6
TrackTime, #7
AnimRate, #8
StartBone, #9
FirstRawFrame, #10
NumRawFrames #11
) = unpack_from('64s64s4i3f3i', chunk_data, chunk_datasize * counter)
action_name = util_bytes_to_str( action_name_raw )
group_name = util_bytes_to_str( group_name_raw )
Raw_Key_Nums += Totalbones * NumRawFrames
Action_List[counter] = ( action_name, group_name, Totalbones, NumRawFrames)
#==============================================================================================
# Raw keys (VQuatAnimKey) 3f vec, 4f quat, 1f time
#==============================================================================================
read_chunk()
if(Raw_Key_Nums != chunk_datacount):
error_callback(
'Raw_Key_Nums Inconsistent.'
'\nData count found: '+chunk_datacount+
'\nRaw_Key_Nums:' + Raw_Key_Nums
)
return False
Raw_Key_List = [None] * chunk_datacount
unpack_data = Struct('3f4f4x').unpack_from
for counter in range(chunk_datacount):
pos = Vector()
quat = Quaternion()
( pos.x, pos.y, pos.z,
quat.x, quat.y, quat.z, quat.w
) = unpack_data( chunk_data, chunk_datasize * counter)
Raw_Key_List[counter] = (pos, quat)
psafile.close()
utils_set_mode('OBJECT')
# index of current frame in raw input data
raw_key_index = 0
util_obj_set_active(context, armature_obj)
gen_name_part = util_gen_name_part(filepath)
armature_obj.animation_data_create()
if bActionsToTrack:
nla_track = armature_obj.animation_data.nla_tracks.new()
nla_track.name = gen_name_part
nla_stripes = nla_track.strips
nla_track_last_frame = 0
else:
is_first_action = True
first_action = None
for counter, (Name, Group, Totalbones, NumRawFrames) in enumerate(Action_List):
ref_time = time.process_time()
if Group != 'None':
Name = "(%s) %s" % (Group,Name)
if bFilenameAsPrefix:
Name = "(%s) %s" % (gen_name_part, Name)
action = bpy.data.actions.new(name = Name)
# force print usefull information to console(due to possible long execution)
print("Action {0:>3d}/{1:<3d} frames: {2:>4d} {3}".format(
counter+1, len(Action_List), NumRawFrames, Name)
)
if first_frames > 0:
maxframes = first_frames
keyframes = min(first_frames, NumRawFrames)
#dev
# keyframes += 1
else:
maxframes = 99999999
keyframes = NumRawFrames
# create all fcurves(for all bones) for an action
# for pose_bone in armature_obj.pose.bones:
for psa_bone in PsaBonesToProcess:
if psa_bone is None:
continue
pose_bone = psa_bone.pose_bone
data_path = pose_bone.path_from_id("rotation_quaternion")
psa_bone.fcurve_quat_w = action.fcurves.new(data_path, index = 0)
psa_bone.fcurve_quat_x = action.fcurves.new(data_path, index = 1)
psa_bone.fcurve_quat_y = action.fcurves.new(data_path, index = 2)
psa_bone.fcurve_quat_z = action.fcurves.new(data_path, index = 3)
data_path = pose_bone.path_from_id("location")
psa_bone.fcurve_loc_x = action.fcurves.new(data_path, index = 0)
psa_bone.fcurve_loc_y = action.fcurves.new(data_path, index = 1)
psa_bone.fcurve_loc_z = action.fcurves.new(data_path, index = 2)
# 1. Pre-add keyframes! \0/
# 2. Set data: keyframe_points[].co[0..1]
# 3. If 2 is not done, do 4: (important!!!)
# 4. "Apply" data: fcurve.update()
# added keyframes points by default is breaking fcurve somehow
# bcs they are all at the same position?
psa_bone.fcurve_quat_w.keyframe_points.add(keyframes)
psa_bone.fcurve_quat_x.keyframe_points.add(keyframes)
psa_bone.fcurve_quat_y.keyframe_points.add(keyframes)
psa_bone.fcurve_quat_z.keyframe_points.add(keyframes)
psa_bone.fcurve_loc_x.keyframe_points.add(keyframes)
psa_bone.fcurve_loc_y.keyframe_points.add(keyframes)
psa_bone.fcurve_loc_z.keyframe_points.add(keyframes)
for i in range(0,min(maxframes, NumRawFrames)):
# raw_key_index+= Totalbones * 5 #55
for j in range(Totalbones):
if j in BoneNotFoundList:
raw_key_index += 1
continue
psa_bone = PsaBonesToProcess[j]
pose_bone = psa_bone.pose_bone
p_pos = Raw_Key_List[raw_key_index][0]
p_quat = Raw_Key_List[raw_key_index][1]
##### Worked with no bone rotation
# quat = p_quat.conjugated() * psa_bone.orig_quat
# loc = p_pos - psa_bone.orig_loc
#####
if psa_bone.parent:
##### Correct
# orig_prot = pose_bone.bone.parent.matrix_local.to_3x3().to_quaternion()
# orig_rot = pose_bone.bone.matrix_local.to_3x3().to_quaternion()
# orig_rot = (orig_prot.conjugated() * orig_rot)
######
#### FINAL
quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
# loc = psa_bone.post_quat.conjugated() * p_pos - psa_bone.post_quat.conjugated() * psa_bone.orig_loc
####
else:
if bDontInvertRoot:
quat = (p_quat.conjugated() * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
else:
quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
loc = psa_bone.post_quat.conjugated() * p_pos - psa_bone.post_quat.conjugated() * psa_bone.orig_loc
pose_bone.rotation_quaternion = quat
pose_bone.location = loc
# pose_bone.rotation_quaternion = orig_rot.conjugated()
# pose_bone.location = p_pos - (pose_bone.bone.matrix_local.translation - pose_bone.bone.parent.matrix_local.translation)
##### Works + post_quat (without location works)
# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
# loc = psa_bone.post_quat.conjugated() * (p_pos - psa_bone.orig_loc)
psa_bone.fcurve_quat_w.keyframe_points[i].co = i, quat.w
psa_bone.fcurve_quat_x.keyframe_points[i].co = i, quat.x
psa_bone.fcurve_quat_y.keyframe_points[i].co = i, quat.y
psa_bone.fcurve_quat_z.keyframe_points[i].co = i, quat.z
psa_bone.fcurve_quat_w.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_quat_x.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_quat_y.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_quat_z.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_loc_x.keyframe_points[i].co = i, loc.x
psa_bone.fcurve_loc_y.keyframe_points[i].co = i, loc.y
psa_bone.fcurve_loc_z.keyframe_points[i].co = i, loc.z
psa_bone.fcurve_loc_x.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_loc_y.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_loc_z.keyframe_points[i].interpolation = fcurve_interpolation
# Old path. Slower.
# psa_bone.fcurve_quat_w.keyframe_points.insert(i,quat.w,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_quat_x.keyframe_points.insert(i,quat.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_quat_y.keyframe_points.insert(i,quat.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_quat_z.keyframe_points.insert(i,quat.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_loc_x.keyframe_points.insert(i,loc.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_loc_y.keyframe_points.insert(i,loc.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_loc_z.keyframe_points.insert(i,loc.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
raw_key_index += 1
# on first frame
# break
raw_key_index += (NumRawFrames-min(maxframes,NumRawFrames)) * Totalbones
# Add action to tail of the nla track
if bActionsToTrack:
if nla_track_last_frame == 0:
nla_stripes.new(Name, 0, action)
else:
nla_stripes.new(Name, nla_stripes[-1].frame_end, action)
nla_track_last_frame += NumRawFrames
elif is_first_action:
first_action = action
is_first_action = False
print("Done: %f sec." % (time.process_time() - ref_time))
# break on first animation set
# break
scene = util_get_scene(context)
if not bActionsToTrack:
if not scene.is_nla_tweakmode:
armature_obj.animation_data.action = first_action
if bUpdateTimelineRange:
scene.frame_start = 0
if bActionsToTrack:
scene.frame_end = sum(frames for _, _, _, frames in Action_List) - 1
else:
scene.frame_end = max(frames for _, _, _, frames in Action_List) - 1
util_select_all(False)
util_obj_select(context, armature_obj)
util_obj_set_active(context, armature_obj)
# 2.8 crashes
if not is_blen_280:
scene.frame_set(0) | [
"def",
"psaimport",
"(",
"filepath",
",",
"context",
"=",
"bpy",
".",
"context",
",",
"oArmature",
"=",
"None",
",",
"bFilenameAsPrefix",
"=",
"False",
",",
"bActionsToTrack",
"=",
"False",
",",
"first_frames",
"=",
"0",
",",
"bDontInvertRoot",
"=",
"False",
",",
"bUpdateTimelineRange",
"=",
"False",
",",
"fcurve_interpolation",
"=",
"'LINEAR'",
",",
"error_callback",
"=",
"__pass",
")",
":",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"print",
"(",
"\"---------EXECUTING PSA PYTHON IMPORTER---------\"",
")",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"file_ext",
"=",
"'psa'",
"try",
":",
"psafile",
"=",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"except",
"IOError",
":",
"error_callback",
"(",
"'Error while opening file for reading:\\n \"'",
"+",
"filepath",
"+",
"'\"'",
")",
"return",
"False",
"print",
"(",
"\"Importing file: \"",
",",
"filepath",
")",
"armature_obj",
"=",
"oArmature",
"if",
"armature_obj",
"is",
"None",
":",
"armature_obj",
"=",
"blen_get_armature_from_selection",
"(",
")",
"if",
"armature_obj",
"is",
"None",
":",
"error_callback",
"(",
"\"No armature selected.\"",
")",
"return",
"False",
"chunk_id",
"=",
"None",
"chunk_type",
"=",
"None",
"chunk_datasize",
"=",
"None",
"chunk_datacount",
"=",
"None",
"chunk_data",
"=",
"None",
"def",
"read_chunk",
"(",
")",
":",
"nonlocal",
"chunk_id",
",",
"chunk_type",
",",
"chunk_datasize",
",",
"chunk_datacount",
",",
"chunk_data",
"(",
"chunk_id",
",",
"chunk_type",
",",
"chunk_datasize",
",",
"chunk_datacount",
")",
"=",
"unpack",
"(",
"'20s3i'",
",",
"psafile",
".",
"read",
"(",
"32",
")",
")",
"chunk_data",
"=",
"psafile",
".",
"read",
"(",
"chunk_datacount",
"*",
"chunk_datasize",
")",
"#============================================================================================== ",
"# General Header",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"if",
"not",
"util_is_header_valid",
"(",
"filepath",
",",
"file_ext",
",",
"chunk_id",
",",
"error_callback",
")",
":",
"return",
"False",
"#============================================================================================== ",
"# Bones (FNamedBoneBinary)",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"psa_bones",
"=",
"{",
"}",
"def",
"new_psa_bone",
"(",
"bone",
",",
"pose_bone",
")",
":",
"psa_bone",
"=",
"class_psa_bone",
"(",
")",
"psa_bones",
"[",
"pose_bone",
".",
"name",
"]",
"=",
"psa_bone",
"psa_bone",
".",
"name",
"=",
"pose_bone",
".",
"name",
"psa_bone",
".",
"pose_bone",
"=",
"pose_bone",
"if",
"bone",
".",
"parent",
"!=",
"None",
":",
"# does needed parent bone was added from psa file",
"if",
"bone",
".",
"parent",
".",
"name",
"in",
"psa_bones",
":",
"psa_bone",
".",
"parent",
"=",
"psa_bones",
"[",
"bone",
".",
"parent",
".",
"name",
"]",
"# no. armature doesnt match",
"else",
":",
"psa_bone",
".",
"parent",
"=",
"None",
"# else:",
"# psa_bone.parent = None",
"psa_bone",
".",
"orig_quat",
"=",
"Quaternion",
"(",
"bone",
"[",
"'orig_quat'",
"]",
")",
"psa_bone",
".",
"orig_loc",
"=",
"Vector",
"(",
"bone",
"[",
"'orig_loc'",
"]",
")",
"psa_bone",
".",
"post_quat",
"=",
"Quaternion",
"(",
"bone",
"[",
"'post_quat'",
"]",
")",
"return",
"psa_bone",
"#Bones Data",
"BoneIndex2Name",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"BoneNotFoundList",
"=",
"[",
"]",
"BonesWithoutAnimation",
"=",
"[",
"]",
"PsaBonesToProcess",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"# printlog(\"Name\\tFlgs\\tNumChld\\tPrntIdx\\tQx\\tQy\\tQz\\tQw\\tLocX\\tLocY\\tLocZ\\tLength\\tXSize\\tYSize\\tZSize\\n\")",
"# for case insensetive comparison",
"# key = lowered name",
"# value = orignal name",
"skeleton_bones_lowered",
"=",
"{",
"}",
"for",
"blender_bone_name",
"in",
"armature_obj",
".",
"data",
".",
"bones",
".",
"keys",
"(",
")",
":",
"skeleton_bones_lowered",
"[",
"blender_bone_name",
".",
"lower",
"(",
")",
"]",
"=",
"blender_bone_name",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"# tPrntIdx is -1 for parent; and 0 for other; no more useful data",
"# indata = unpack_from('64s3i11f', chunk_data, chunk_datasize * counter)",
"(",
"indata",
")",
"=",
"unpack_from",
"(",
"'64s56x'",
",",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"in_name",
"=",
"util_bytes_to_str",
"(",
"indata",
"[",
"0",
"]",
")",
"# bonename = util_bytes_to_str(indata[0]).upper()",
"in_name_lowered",
"=",
"in_name",
".",
"lower",
"(",
")",
"if",
"in_name_lowered",
"in",
"skeleton_bones_lowered",
":",
"orig_name",
"=",
"skeleton_bones_lowered",
"[",
"in_name_lowered",
"]",
"# use a skeleton bone name ",
"BoneIndex2Name",
"[",
"counter",
"]",
"=",
"orig_name",
"PsaBonesToProcess",
"[",
"counter",
"]",
"=",
"new_psa_bone",
"(",
"armature_obj",
".",
"data",
".",
"bones",
"[",
"orig_name",
"]",
",",
"armature_obj",
".",
"pose",
".",
"bones",
"[",
"orig_name",
"]",
")",
"else",
":",
"# print(\"Can't find the bone:\", bonename)",
"BoneNotFoundList",
".",
"append",
"(",
"counter",
")",
"if",
"len",
"(",
"psa_bones",
")",
"==",
"0",
":",
"error_callback",
"(",
"'No bone was match!\\nSkip import!'",
")",
"return",
"False",
"# does anyone care?",
"for",
"blender_bone_name",
"in",
"armature_obj",
".",
"data",
".",
"bones",
".",
"keys",
"(",
")",
":",
"if",
"BoneIndex2Name",
".",
"count",
"(",
"blender_bone_name",
")",
"==",
"0",
":",
"BonesWithoutAnimation",
".",
"append",
"(",
"blender_bone_name",
")",
"if",
"len",
"(",
"BoneNotFoundList",
")",
">",
"0",
":",
"print",
"(",
"'Not found bones: %i.'",
"%",
"len",
"(",
"BoneNotFoundList",
")",
")",
"if",
"len",
"(",
"BonesWithoutAnimation",
")",
">",
"0",
":",
"print",
"(",
"'Bones(%i) without animation data:\\n'",
"%",
"len",
"(",
"BonesWithoutAnimation",
")",
",",
"', '",
".",
"join",
"(",
"BonesWithoutAnimation",
")",
")",
"#============================================================================================== ",
"# Animations (AniminfoBinary)",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"Raw_Key_Nums",
"=",
"0",
"Action_List",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"action_name_raw",
",",
"#0",
"group_name_raw",
",",
"#1",
"Totalbones",
",",
"#2",
"RootInclude",
",",
"#3",
"KeyCompressionStyle",
",",
"#4",
"KeyQuotum",
",",
"#5",
"KeyReduction",
",",
"#6",
"TrackTime",
",",
"#7",
"AnimRate",
",",
"#8",
"StartBone",
",",
"#9",
"FirstRawFrame",
",",
"#10",
"NumRawFrames",
"#11",
")",
"=",
"unpack_from",
"(",
"'64s64s4i3f3i'",
",",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"action_name",
"=",
"util_bytes_to_str",
"(",
"action_name_raw",
")",
"group_name",
"=",
"util_bytes_to_str",
"(",
"group_name_raw",
")",
"Raw_Key_Nums",
"+=",
"Totalbones",
"*",
"NumRawFrames",
"Action_List",
"[",
"counter",
"]",
"=",
"(",
"action_name",
",",
"group_name",
",",
"Totalbones",
",",
"NumRawFrames",
")",
"#============================================================================================== ",
"# Raw keys (VQuatAnimKey) 3f vec, 4f quat, 1f time",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"if",
"(",
"Raw_Key_Nums",
"!=",
"chunk_datacount",
")",
":",
"error_callback",
"(",
"'Raw_Key_Nums Inconsistent.'",
"'\\nData count found: '",
"+",
"chunk_datacount",
"+",
"'\\nRaw_Key_Nums:'",
"+",
"Raw_Key_Nums",
")",
"return",
"False",
"Raw_Key_List",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'3f4f4x'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"pos",
"=",
"Vector",
"(",
")",
"quat",
"=",
"Quaternion",
"(",
")",
"(",
"pos",
".",
"x",
",",
"pos",
".",
"y",
",",
"pos",
".",
"z",
",",
"quat",
".",
"x",
",",
"quat",
".",
"y",
",",
"quat",
".",
"z",
",",
"quat",
".",
"w",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"Raw_Key_List",
"[",
"counter",
"]",
"=",
"(",
"pos",
",",
"quat",
")",
"psafile",
".",
"close",
"(",
")",
"utils_set_mode",
"(",
"'OBJECT'",
")",
"# index of current frame in raw input data",
"raw_key_index",
"=",
"0",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")",
"gen_name_part",
"=",
"util_gen_name_part",
"(",
"filepath",
")",
"armature_obj",
".",
"animation_data_create",
"(",
")",
"if",
"bActionsToTrack",
":",
"nla_track",
"=",
"armature_obj",
".",
"animation_data",
".",
"nla_tracks",
".",
"new",
"(",
")",
"nla_track",
".",
"name",
"=",
"gen_name_part",
"nla_stripes",
"=",
"nla_track",
".",
"strips",
"nla_track_last_frame",
"=",
"0",
"else",
":",
"is_first_action",
"=",
"True",
"first_action",
"=",
"None",
"for",
"counter",
",",
"(",
"Name",
",",
"Group",
",",
"Totalbones",
",",
"NumRawFrames",
")",
"in",
"enumerate",
"(",
"Action_List",
")",
":",
"ref_time",
"=",
"time",
".",
"process_time",
"(",
")",
"if",
"Group",
"!=",
"'None'",
":",
"Name",
"=",
"\"(%s) %s\"",
"%",
"(",
"Group",
",",
"Name",
")",
"if",
"bFilenameAsPrefix",
":",
"Name",
"=",
"\"(%s) %s\"",
"%",
"(",
"gen_name_part",
",",
"Name",
")",
"action",
"=",
"bpy",
".",
"data",
".",
"actions",
".",
"new",
"(",
"name",
"=",
"Name",
")",
"# force print usefull information to console(due to possible long execution)",
"print",
"(",
"\"Action {0:>3d}/{1:<3d} frames: {2:>4d} {3}\"",
".",
"format",
"(",
"counter",
"+",
"1",
",",
"len",
"(",
"Action_List",
")",
",",
"NumRawFrames",
",",
"Name",
")",
")",
"if",
"first_frames",
">",
"0",
":",
"maxframes",
"=",
"first_frames",
"keyframes",
"=",
"min",
"(",
"first_frames",
",",
"NumRawFrames",
")",
"#dev",
"# keyframes += 1",
"else",
":",
"maxframes",
"=",
"99999999",
"keyframes",
"=",
"NumRawFrames",
"# create all fcurves(for all bones) for an action",
"# for pose_bone in armature_obj.pose.bones:",
"for",
"psa_bone",
"in",
"PsaBonesToProcess",
":",
"if",
"psa_bone",
"is",
"None",
":",
"continue",
"pose_bone",
"=",
"psa_bone",
".",
"pose_bone",
"data_path",
"=",
"pose_bone",
".",
"path_from_id",
"(",
"\"rotation_quaternion\"",
")",
"psa_bone",
".",
"fcurve_quat_w",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"0",
")",
"psa_bone",
".",
"fcurve_quat_x",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"1",
")",
"psa_bone",
".",
"fcurve_quat_y",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"2",
")",
"psa_bone",
".",
"fcurve_quat_z",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"3",
")",
"data_path",
"=",
"pose_bone",
".",
"path_from_id",
"(",
"\"location\"",
")",
"psa_bone",
".",
"fcurve_loc_x",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"0",
")",
"psa_bone",
".",
"fcurve_loc_y",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"1",
")",
"psa_bone",
".",
"fcurve_loc_z",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"2",
")",
"# 1. Pre-add keyframes! \\0/",
"# 2. Set data: keyframe_points[].co[0..1]",
"# 3. If 2 is not done, do 4: (important!!!)",
"# 4. \"Apply\" data: fcurve.update()",
"# added keyframes points by default is breaking fcurve somehow",
"# bcs they are all at the same position?",
"psa_bone",
".",
"fcurve_quat_w",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_quat_x",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_quat_y",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_quat_z",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_loc_x",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_loc_y",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_loc_z",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"maxframes",
",",
"NumRawFrames",
")",
")",
":",
"# raw_key_index+= Totalbones * 5 #55",
"for",
"j",
"in",
"range",
"(",
"Totalbones",
")",
":",
"if",
"j",
"in",
"BoneNotFoundList",
":",
"raw_key_index",
"+=",
"1",
"continue",
"psa_bone",
"=",
"PsaBonesToProcess",
"[",
"j",
"]",
"pose_bone",
"=",
"psa_bone",
".",
"pose_bone",
"p_pos",
"=",
"Raw_Key_List",
"[",
"raw_key_index",
"]",
"[",
"0",
"]",
"p_quat",
"=",
"Raw_Key_List",
"[",
"raw_key_index",
"]",
"[",
"1",
"]",
"##### Worked with no bone rotation",
"# quat = p_quat.conjugated() * psa_bone.orig_quat",
"# loc = p_pos - psa_bone.orig_loc",
"#####",
"if",
"psa_bone",
".",
"parent",
":",
"##### Correct",
"# orig_prot = pose_bone.bone.parent.matrix_local.to_3x3().to_quaternion()",
"# orig_rot = pose_bone.bone.matrix_local.to_3x3().to_quaternion()",
"# orig_rot = (orig_prot.conjugated() * orig_rot)",
"######",
"#### FINAL",
"quat",
"=",
"(",
"p_quat",
"*",
"psa_bone",
".",
"post_quat",
")",
".",
"conjugated",
"(",
")",
"*",
"(",
"psa_bone",
".",
"orig_quat",
"*",
"psa_bone",
".",
"post_quat",
")",
"# loc = psa_bone.post_quat.conjugated() * p_pos - psa_bone.post_quat.conjugated() * psa_bone.orig_loc",
"####",
"else",
":",
"if",
"bDontInvertRoot",
":",
"quat",
"=",
"(",
"p_quat",
".",
"conjugated",
"(",
")",
"*",
"psa_bone",
".",
"post_quat",
")",
".",
"conjugated",
"(",
")",
"*",
"(",
"psa_bone",
".",
"orig_quat",
"*",
"psa_bone",
".",
"post_quat",
")",
"else",
":",
"quat",
"=",
"(",
"p_quat",
"*",
"psa_bone",
".",
"post_quat",
")",
".",
"conjugated",
"(",
")",
"*",
"(",
"psa_bone",
".",
"orig_quat",
"*",
"psa_bone",
".",
"post_quat",
")",
"loc",
"=",
"psa_bone",
".",
"post_quat",
".",
"conjugated",
"(",
")",
"*",
"p_pos",
"-",
"psa_bone",
".",
"post_quat",
".",
"conjugated",
"(",
")",
"*",
"psa_bone",
".",
"orig_loc",
"pose_bone",
".",
"rotation_quaternion",
"=",
"quat",
"pose_bone",
".",
"location",
"=",
"loc",
"# pose_bone.rotation_quaternion = orig_rot.conjugated()",
"# pose_bone.location = p_pos - (pose_bone.bone.matrix_local.translation - pose_bone.bone.parent.matrix_local.translation)",
"##### Works + post_quat (without location works)",
"# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)",
"# loc = psa_bone.post_quat.conjugated() * (p_pos - psa_bone.orig_loc)",
"psa_bone",
".",
"fcurve_quat_w",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"w",
"psa_bone",
".",
"fcurve_quat_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"x",
"psa_bone",
".",
"fcurve_quat_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"y",
"psa_bone",
".",
"fcurve_quat_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"z",
"psa_bone",
".",
"fcurve_quat_w",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_quat_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_quat_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_quat_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_loc_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"loc",
".",
"x",
"psa_bone",
".",
"fcurve_loc_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"loc",
".",
"y",
"psa_bone",
".",
"fcurve_loc_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"loc",
".",
"z",
"psa_bone",
".",
"fcurve_loc_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_loc_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_loc_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"# Old path. Slower.",
"# psa_bone.fcurve_quat_w.keyframe_points.insert(i,quat.w,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_quat_x.keyframe_points.insert(i,quat.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_quat_y.keyframe_points.insert(i,quat.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_quat_z.keyframe_points.insert(i,quat.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_loc_x.keyframe_points.insert(i,loc.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_loc_y.keyframe_points.insert(i,loc.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_loc_z.keyframe_points.insert(i,loc.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"raw_key_index",
"+=",
"1",
"# on first frame",
"# break",
"raw_key_index",
"+=",
"(",
"NumRawFrames",
"-",
"min",
"(",
"maxframes",
",",
"NumRawFrames",
")",
")",
"*",
"Totalbones",
"# Add action to tail of the nla track",
"if",
"bActionsToTrack",
":",
"if",
"nla_track_last_frame",
"==",
"0",
":",
"nla_stripes",
".",
"new",
"(",
"Name",
",",
"0",
",",
"action",
")",
"else",
":",
"nla_stripes",
".",
"new",
"(",
"Name",
",",
"nla_stripes",
"[",
"-",
"1",
"]",
".",
"frame_end",
",",
"action",
")",
"nla_track_last_frame",
"+=",
"NumRawFrames",
"elif",
"is_first_action",
":",
"first_action",
"=",
"action",
"is_first_action",
"=",
"False",
"print",
"(",
"\"Done: %f sec.\"",
"%",
"(",
"time",
".",
"process_time",
"(",
")",
"-",
"ref_time",
")",
")",
"# break on first animation set",
"# break",
"scene",
"=",
"util_get_scene",
"(",
"context",
")",
"if",
"not",
"bActionsToTrack",
":",
"if",
"not",
"scene",
".",
"is_nla_tweakmode",
":",
"armature_obj",
".",
"animation_data",
".",
"action",
"=",
"first_action",
"if",
"bUpdateTimelineRange",
":",
"scene",
".",
"frame_start",
"=",
"0",
"if",
"bActionsToTrack",
":",
"scene",
".",
"frame_end",
"=",
"sum",
"(",
"frames",
"for",
"_",
",",
"_",
",",
"_",
",",
"frames",
"in",
"Action_List",
")",
"-",
"1",
"else",
":",
"scene",
".",
"frame_end",
"=",
"max",
"(",
"frames",
"for",
"_",
",",
"_",
",",
"_",
",",
"frames",
"in",
"Action_List",
")",
"-",
"1",
"util_select_all",
"(",
"False",
")",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")",
"# 2.8 crashes",
"if",
"not",
"is_blen_280",
":",
"scene",
".",
"frame_set",
"(",
"0",
")"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_270.py#L1078-L1484 |
||
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_280.py | python | util_is_header_valid | (filename, file_ext, chunk_id, error_callback) | return True | Return True if chunk_id is a valid psk/psa (file_ext) 'magick number'. | Return True if chunk_id is a valid psk/psa (file_ext) 'magick number'. | [
"Return",
"True",
"if",
"chunk_id",
"is",
"a",
"valid",
"psk",
"/",
"psa",
"(",
"file_ext",
")",
"magick",
"number",
"."
] | def util_is_header_valid(filename, file_ext, chunk_id, error_callback):
'''Return True if chunk_id is a valid psk/psa (file_ext) 'magick number'.'''
if chunk_id != PSKPSA_FILE_HEADER[file_ext]:
error_callback(
"File %s is not a %s file. (header mismach)\nExpected: %s \nPresent %s" % (
filename, file_ext,
PSKPSA_FILE_HEADER[file_ext], chunk_id)
)
return False
return True | [
"def",
"util_is_header_valid",
"(",
"filename",
",",
"file_ext",
",",
"chunk_id",
",",
"error_callback",
")",
":",
"if",
"chunk_id",
"!=",
"PSKPSA_FILE_HEADER",
"[",
"file_ext",
"]",
":",
"error_callback",
"(",
"\"File %s is not a %s file. (header mismach)\\nExpected: %s \\nPresent %s\"",
"%",
"(",
"filename",
",",
"file_ext",
",",
"PSKPSA_FILE_HEADER",
"[",
"file_ext",
"]",
",",
"chunk_id",
")",
")",
"return",
"False",
"return",
"True"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_280.py#L171-L180 |
|
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_280.py | python | util_gen_name_part | (filepath) | return re.match(r'.*[/\\]([^/\\]+?)(\..{2,5})?$', filepath).group(1) | Return file name without extension | Return file name without extension | [
"Return",
"file",
"name",
"without",
"extension"
] | def util_gen_name_part(filepath):
'''Return file name without extension'''
return re.match(r'.*[/\\]([^/\\]+?)(\..{2,5})?$', filepath).group(1) | [
"def",
"util_gen_name_part",
"(",
"filepath",
")",
":",
"return",
"re",
".",
"match",
"(",
"r'.*[/\\\\]([^/\\\\]+?)(\\..{2,5})?$'",
",",
"filepath",
")",
".",
"group",
"(",
"1",
")"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_280.py#L183-L185 |
|
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_280.py | python | vec_to_axis_vec | (vec_in, vec_out) | Make **vec_out** to be an axis-aligned unit vector that is closest to vec_in. (basis?) | Make **vec_out** to be an axis-aligned unit vector that is closest to vec_in. (basis?) | [
"Make",
"**",
"vec_out",
"**",
"to",
"be",
"an",
"axis",
"-",
"aligned",
"unit",
"vector",
"that",
"is",
"closest",
"to",
"vec_in",
".",
"(",
"basis?",
")"
] | def vec_to_axis_vec(vec_in, vec_out):
'''Make **vec_out** to be an axis-aligned unit vector that is closest to vec_in. (basis?)'''
x, y, z = vec_in
if abs(x) > abs(y):
if abs(x) > abs(z):
vec_out.x = 1 if x >= 0 else -1
else:
vec_out.z = 1 if z >= 0 else -1
else:
if abs(y) > abs(z):
vec_out.y = 1 if y >= 0 else -1
else:
vec_out.z = 1 if z >= 0 else -1 | [
"def",
"vec_to_axis_vec",
"(",
"vec_in",
",",
"vec_out",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"vec_in",
"if",
"abs",
"(",
"x",
")",
">",
"abs",
"(",
"y",
")",
":",
"if",
"abs",
"(",
"x",
")",
">",
"abs",
"(",
"z",
")",
":",
"vec_out",
".",
"x",
"=",
"1",
"if",
"x",
">=",
"0",
"else",
"-",
"1",
"else",
":",
"vec_out",
".",
"z",
"=",
"1",
"if",
"z",
">=",
"0",
"else",
"-",
"1",
"else",
":",
"if",
"abs",
"(",
"y",
")",
">",
"abs",
"(",
"z",
")",
":",
"vec_out",
".",
"y",
"=",
"1",
"if",
"y",
">=",
"0",
"else",
"-",
"1",
"else",
":",
"vec_out",
".",
"z",
"=",
"1",
"if",
"z",
">=",
"0",
"else",
"-",
"1"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_280.py#L188-L200 |
||
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_280.py | python | color_linear_to_srgb | (c) | Convert from linear to sRGB color space.
Source: Cycles addon implementation, node_color.h. | Convert from linear to sRGB color space.
Source: Cycles addon implementation, node_color.h. | [
"Convert",
"from",
"linear",
"to",
"sRGB",
"color",
"space",
".",
"Source",
":",
"Cycles",
"addon",
"implementation",
"node_color",
".",
"h",
"."
] | def color_linear_to_srgb(c):
"""
Convert from linear to sRGB color space.
Source: Cycles addon implementation, node_color.h.
"""
if c < 0.0031308:
return 0.0 if c < 0.0 else c * 12.92
else:
return 1.055 * pow(c, 1.0 / 2.4) - 0.055 | [
"def",
"color_linear_to_srgb",
"(",
"c",
")",
":",
"if",
"c",
"<",
"0.0031308",
":",
"return",
"0.0",
"if",
"c",
"<",
"0.0",
"else",
"c",
"*",
"12.92",
"else",
":",
"return",
"1.055",
"*",
"pow",
"(",
"c",
",",
"1.0",
"/",
"2.4",
")",
"-",
"0.055"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_280.py#L295-L303 |
||
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_280.py | python | pskimport | (filepath,
context = None,
bImportmesh = True,
bImportbone = True,
bSpltiUVdata = False,
fBonesize = 5.0,
fBonesizeRatio = 0.6,
bDontInvertRoot = True,
bReorientBones = False,
bReorientDirectly = False,
bScaleDown = True,
bToSRGB = True,
error_callback = None) | return True | Import mesh and skeleton from .psk/.pskx files
Args:
bReorientBones:
Axis based bone orientation to children
error_callback:
Called when importing is failed.
error_callback = lambda msg: print('reason:', msg) | Import mesh and skeleton from .psk/.pskx files
Args:
bReorientBones:
Axis based bone orientation to children
error_callback:
Called when importing is failed.
error_callback = lambda msg: print('reason:', msg) | [
"Import",
"mesh",
"and",
"skeleton",
"from",
".",
"psk",
"/",
".",
"pskx",
"files",
"Args",
":",
"bReorientBones",
":",
"Axis",
"based",
"bone",
"orientation",
"to",
"children",
"error_callback",
":",
"Called",
"when",
"importing",
"is",
"failed",
".",
"error_callback",
"=",
"lambda",
"msg",
":",
"print",
"(",
"reason",
":",
"msg",
")"
] | def pskimport(filepath,
context = None,
bImportmesh = True,
bImportbone = True,
bSpltiUVdata = False,
fBonesize = 5.0,
fBonesizeRatio = 0.6,
bDontInvertRoot = True,
bReorientBones = False,
bReorientDirectly = False,
bScaleDown = True,
bToSRGB = True,
error_callback = None):
'''
Import mesh and skeleton from .psk/.pskx files
Args:
bReorientBones:
Axis based bone orientation to children
error_callback:
Called when importing is failed.
error_callback = lambda msg: print('reason:', msg)
'''
if not hasattr( error_callback, '__call__'):
# error_callback = __pass
error_callback = print
# ref_time = time.process_time()
if not bImportbone and not bImportmesh:
error_callback("Nothing to do.\nSet something for import.")
return False
print ("-----------------------------------------------")
print ("---------EXECUTING PSK PYTHON IMPORTER---------")
print ("-----------------------------------------------")
#file may not exist
try:
file = open(filepath,'rb')
except IOError:
error_callback('Error while opening file for reading:\n "'+filepath+'"')
return False
if not util_check_file_header(file, 'psk'):
error_callback('Not psk file:\n "'+filepath+'"')
return False
Vertices = None
Wedges = None
Faces = None
UV_by_face = None
Materials = None
Bones = None
Weights = None
VertexColors = None
Extrauvs = []
Normals = None
WedgeIdx_by_faceIdx = None
if not context:
context = bpy.context
#==================================================================================================
# Materials MaterialNameRaw | TextureIndex | PolyFlags | AuxMaterial | AuxFlags | LodBias | LodStyle
# Only Name is usable.
def read_materials():
nonlocal Materials
Materials = []
for counter in range(chunk_datacount):
(MaterialNameRaw,) = unpack_from('64s24x', chunk_data, chunk_datasize * counter)
Materials.append( util_bytes_to_str( MaterialNameRaw ) )
#==================================================================================================
# Faces WdgIdx1 | WdgIdx2 | WdgIdx3 | MatIdx | AuxMatIdx | SmthGrp
def read_faces():
if not bImportmesh:
return True
nonlocal Faces, UV_by_face, WedgeIdx_by_faceIdx
UV_by_face = [None] * chunk_datacount
Faces = [None] * chunk_datacount
WedgeIdx_by_faceIdx = [None] * chunk_datacount
if len(Wedges) > 65536:
unpack_format = '=IIIBBI'
else:
unpack_format = '=HHHBBI'
unpack_data = Struct(unpack_format).unpack_from
for counter in range(chunk_datacount):
(WdgIdx1, WdgIdx2, WdgIdx3,
MatIndex,
AuxMatIndex, #unused
SmoothingGroup # Umodel is not exporting SmoothingGroups
) = unpack_data(chunk_data, counter * chunk_datasize)
# looks ugly
# Wedges is (point_index, u, v, MatIdx)
((vertid0, u0, v0, matid0), (vertid1, u1, v1, matid1), (vertid2, u2, v2, matid2)) = Wedges[WdgIdx1], Wedges[WdgIdx2], Wedges[WdgIdx3]
# note order: C,B,A
# Faces[counter] = (vertid2, vertid1, vertid0)
Faces[counter] = (vertid1, vertid0, vertid2)
# Faces[counter] = (vertid1, vertid2, vertid0)
# Faces[counter] = (vertid0, vertid1, vertid2)
# uv = ( ( u2, 1.0 - v2 ), ( u1, 1.0 - v1 ), ( u0, 1.0 - v0 ) )
uv = ( ( u1, 1.0 - v1 ), ( u0, 1.0 - v0 ), ( u2, 1.0 - v2 ) )
# Mapping: FaceIndex <=> UV data <=> FaceMatIndex
UV_by_face[counter] = (uv, MatIndex, (matid2, matid1, matid0))
# We need this for EXTRA UVs
WedgeIdx_by_faceIdx[counter] = (WdgIdx3, WdgIdx2, WdgIdx1)
#==================================================================================================
# Vertices X | Y | Z
def read_vertices():
if not bImportmesh:
return True
nonlocal Vertices
Vertices = [None] * chunk_datacount
unpack_data = Struct('3f').unpack_from
if bScaleDown:
for counter in range( chunk_datacount ):
(vec_x, vec_y, vec_z) = unpack_data(chunk_data, counter * chunk_datasize)
Vertices[counter] = (vec_x*0.01, vec_y*0.01, vec_z*0.01)
# equal to gltf
# Vertices[counter] = (vec_x*0.01, vec_z*0.01, -vec_y*0.01)
else:
for counter in range( chunk_datacount ):
Vertices[counter] = unpack_data(chunk_data, counter * chunk_datasize)
#==================================================================================================
# Wedges (UV) VertexId | U | V | MatIdx
def read_wedges():
if not bImportmesh:
return True
nonlocal Wedges
Wedges = [None] * chunk_datacount
unpack_data = Struct('=IffBxxx').unpack_from
for counter in range( chunk_datacount ):
(vertex_id,
u, v,
material_index) = unpack_data( chunk_data, counter * chunk_datasize )
# print(vertex_id, u, v, material_index)
# Wedges[counter] = (vertex_id, u, v, material_index)
Wedges[counter] = [vertex_id, u, v, material_index]
#==================================================================================================
# Bones (VBone .. VJointPos ) Name|Flgs|NumChld|PrntIdx|Qw|Qx|Qy|Qz|LocX|LocY|LocZ|Lngth|XSize|YSize|ZSize
def read_bones():
nonlocal Bones, bImportbone
if chunk_datacount == 0:
bImportbone = False
if bImportbone:
# unpack_data = Struct('64s3i11f').unpack_from
unpack_data = Struct('64s3i7f16x').unpack_from
else:
unpack_data = Struct('64s56x').unpack_from
Bones = [None] * chunk_datacount
for counter in range( chunk_datacount ):
Bones[counter] = unpack_data( chunk_data, chunk_datasize * counter)
#==================================================================================================
# Influences (Bone Weight) (VRawBoneInfluence) ( Weight | PntIdx | BoneIdx)
def read_weights():
nonlocal Weights
if not bImportmesh:
return True
Weights = [None] * chunk_datacount
unpack_data = Struct('fii').unpack_from
for counter in range(chunk_datacount):
Weights[counter] = unpack_data(chunk_data, chunk_datasize * counter)
#==================================================================================================
# Vertex colors. R G B A bytes. NOTE: it is Wedge color.(uses Wedges index)
def read_vertex_colors():
nonlocal VertexColors
unpack_data = Struct("=4B").unpack_from
VertexColors = [None] * chunk_datacount
for counter in range( chunk_datacount ):
VertexColors[counter] = unpack_data(chunk_data, chunk_datasize * counter)
#==================================================================================================
# Extra UV. U | V
def read_extrauvs():
unpack_data = Struct("=2f").unpack_from
uvdata = [None] * chunk_datacount
for counter in range( chunk_datacount ):
uvdata[counter] = unpack_data(chunk_data, chunk_datasize * counter)
Extrauvs.append(uvdata)
#==================================================================================================
# Vertex Normals NX | NY | NZ
def read_normals():
if not bImportmesh:
return True
nonlocal Normals
Normals = [None] * chunk_datacount
unpack_data = Struct('3f').unpack_from
for counter in range(chunk_datacount):
Normals[counter] = unpack_data(chunk_data, counter * chunk_datasize)
CHUNKS_HANDLERS = {
'PNTS0000': read_vertices,
'VTXW0000': read_wedges,
'VTXW3200': read_wedges,#?
'FACE0000': read_faces,
'FACE3200': read_faces,
'MATT0000': read_materials,
'REFSKELT': read_bones,
'REFSKEL0': read_bones, #?
'RAWW0000': read_weights,
'RAWWEIGH': read_weights,
'VERTEXCO': read_vertex_colors, # VERTEXCOLOR
'EXTRAUVS': read_extrauvs,
'VTXNORMS': read_normals
}
#===================================================================================================
# File. Read all needed data.
# VChunkHeader Struct
# ChunkID|TypeFlag|DataSize|DataCount
# 0 |1 |2 |3
while True:
header_bytes = file.read(32)
if len(header_bytes) < 32:
if len(header_bytes) != 0:
error_callback("Unexpected end of file.(%s/32 bytes)" % len(header_bytes))
break
(chunk_id, chunk_type, chunk_datasize, chunk_datacount) = unpack('20s3i', header_bytes)
chunk_id_str = util_bytes_to_str(chunk_id)
chunk_id_str = chunk_id_str[:8]
if chunk_id_str in CHUNKS_HANDLERS:
chunk_data = file.read( chunk_datasize * chunk_datacount)
if len(chunk_data) < chunk_datasize * chunk_datacount:
error_callback('Psk chunk %s is broken.' % chunk_id_str)
return False
CHUNKS_HANDLERS[chunk_id_str]()
else:
print('Unknown chunk: ', chunk_id_str)
file.seek(chunk_datasize * chunk_datacount, 1)
# print(chunk_id_str, chunk_datacount)
file.close()
print(" Importing file:", filepath)
if not bImportmesh and (Bones is None or len(Bones) == 0):
error_callback("Psk: no skeleton data.")
return False
MAX_UVS = 8
NAME_UV_PREFIX = "UV"
# file name w/out extension
gen_name_part = util_gen_name_part(filepath)
gen_names = {
'armature_object': gen_name_part + '.ao',
'armature_data': gen_name_part + '.ad',
'mesh_object': gen_name_part + '.mo',
'mesh_data': gen_name_part + '.md'
}
if bImportmesh:
mesh_data = bpy.data.meshes.new(gen_names['mesh_data'])
mesh_obj = bpy.data.objects.new(gen_names['mesh_object'], mesh_data)
#==================================================================================================
# UV. Prepare
if bImportmesh:
if bSpltiUVdata:
# store how much each "matrial index" have vertices
uv_mat_ids = {}
for (_, _, _, material_index) in Wedges:
if not (material_index in uv_mat_ids):
uv_mat_ids[material_index] = 1
else:
uv_mat_ids[material_index] += 1
# if we have more UV material indexes than blender UV maps, then...
if bSpltiUVdata and len(uv_mat_ids) > MAX_UVS :
uv_mat_ids_len = len(uv_mat_ids)
print('UVs: %s out of %s is combined in a first UV map(%s0)' % (uv_mat_ids_len - 8, uv_mat_ids_len, NAME_UV_PREFIX))
mat_idx_proxy = [0] * len(uv_mat_ids)
counts_sorted = sorted(uv_mat_ids.values(), reverse = True)
new_mat_index = MAX_UVS - 1
for c in counts_sorted:
for mat_idx, counts in uv_mat_ids.items():
if c == counts:
mat_idx_proxy[mat_idx] = new_mat_index
if new_mat_index > 0:
new_mat_index -= 1
# print('MatIdx remap: %s > %s' % (mat_idx,new_mat_index))
for i in range(len(Wedges)):
Wedges[i][3] = mat_idx_proxy[Wedges[i][3]]
# print('Wedges:', chunk_datacount)
# print('uv_mat_ids', uv_mat_ids)
# print('uv_mat_ids', uv_mat_ids)
# for w in Wedges:
if bImportmesh:
# print("-- Materials -- (index, name, faces)")
blen_materials = []
for materialname in Materials:
matdata = bpy.data.materials.get(materialname)
if matdata is None:
matdata = bpy.data.materials.new( materialname )
# matdata = bpy.data.materials.new( materialname )
blen_materials.append( matdata )
mesh_data.materials.append( matdata )
# print(counter,materialname,TextureIndex)
# if mat_groups.get(counter) is not None:
# print("%i: %s" % (counter, materialname), len(mat_groups[counter]))
#==================================================================================================
# Prepare bone data
def init_psk_bone(i, psk_bones, name_raw):
psk_bone = class_psk_bone()
psk_bone.children = []
psk_bone.name = util_bytes_to_str(name_raw)
psk_bones[i] = psk_bone
return psk_bone
psk_bone_name_toolong = False
# indexed by bone index. array of psk_bone
psk_bones = [None] * len(Bones)
if not bImportbone: #data needed for mesh-only import
for counter,(name_raw,) in enumerate(Bones):
init_psk_bone(counter, psk_bones, name_raw)
if bImportbone: #else?
# average bone length
sum_bone_pos = 0
for counter, (name_raw, flags, NumChildren, ParentIndex, #0 1 2 3
quat_x, quat_y, quat_z, quat_w, #4 5 6 7
vec_x, vec_y, vec_z
# , #8 9 10
# joint_length, #11
# scale_x, scale_y, scale_z
) in enumerate(Bones):
psk_bone = init_psk_bone(counter, psk_bones, name_raw)
psk_bone.bone_index = counter
psk_bone.parent_index = ParentIndex
# Tested. 64 is getting cut to 63
if len(psk_bone.name) > 63:
psk_bone_name_toolong = True
# print('Warning. Bone name is too long:', psk_bone.name)
# make sure we have valid parent_index
if psk_bone.parent_index < 0:
psk_bone.parent_index = 0
# psk_bone.scale = (scale_x, scale_y, scale_z)
# print("%s: %03f %03f | %f" % (psk_bone.name, scale_x, scale_y, joint_length),scale_x)
# print("%s:" % (psk_bone.name), vec_x, quat_x)
# store bind pose to make it available for psa-import via CustomProperty of the Blender bone
psk_bone.orig_quat = Quaternion((quat_w, quat_x, quat_y, quat_z))
if bScaleDown:
psk_bone.orig_loc = Vector((vec_x * 0.01, vec_y * 0.01, vec_z * 0.01))
else:
psk_bone.orig_loc = Vector((vec_x, vec_y, vec_z))
# root bone must have parent_index = 0 and selfindex = 0
if psk_bone.parent_index == 0 and psk_bone.bone_index == psk_bone.parent_index:
if bDontInvertRoot:
psk_bone.mat_world_rot = psk_bone.orig_quat.to_matrix()
else:
psk_bone.mat_world_rot = psk_bone.orig_quat.conjugated().to_matrix()
psk_bone.mat_world = Matrix.Translation(psk_bone.orig_loc)
sum_bone_pos += psk_bone.orig_loc.length
#==================================================================================================
# Bones. Calc World-space matrix
# TODO optimize math.
for psk_bone in psk_bones:
if psk_bone.parent_index == 0:
if psk_bone.bone_index == 0:
psk_bone.parent = None
continue
parent = psk_bones[psk_bone.parent_index]
psk_bone.parent = parent
parent.children.append(psk_bone)
# mat_world - world space bone matrix WITHOUT own rotation
# mat_world_rot - world space bone rotation WITH own rotation
# psk_bone.mat_world = parent.mat_world_rot.to_4x4()
# psk_bone.mat_world.translation = parent.mat_world.translation + parent.mat_world_rot * psk_bone.orig_loc
# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()
psk_bone.mat_world = parent.mat_world_rot.to_4x4()
v = psk_bone.orig_loc.copy()
v.rotate( parent.mat_world_rot )
psk_bone.mat_world.translation = parent.mat_world.translation + v
psk_bone.mat_world_rot = psk_bone.orig_quat.conjugated().to_matrix()
psk_bone.mat_world_rot.rotate( parent.mat_world_rot )
# psk_bone.mat_world = ( parent.mat_world_rot.to_4x4() * psk_bone.trans)
# psk_bone.mat_world.translation += parent.mat_world.translation
# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()
#==================================================================================================
# Skeleton. Prepare.
armature_data = bpy.data.armatures.new(gen_names['armature_data'])
armature_obj = bpy.data.objects.new(gen_names['armature_object'], armature_data)
# TODO: options for axes and x_ray?
armature_data.show_axes = False
armature_data.display_type = 'STICK'
armature_obj.show_in_front = True
util_obj_link(context, armature_obj)
util_select_all(False)
util_obj_select(context, armature_obj)
util_obj_set_active(context, armature_obj)
utils_set_mode('EDIT')
sum_bone_pos /= len(Bones) # average
sum_bone_pos *= fBonesizeRatio # corrected
# bone_size_choosen = max(0.01, round((min(sum_bone_pos, fBonesize))))
bone_size_choosen = max(0.01, round((min(sum_bone_pos, fBonesize))*100)/100)
# bone_size_choosen = max(0.01, min(sum_bone_pos, fBonesize))
# print("Bonesize %f | old: %f round: %f" % (bone_size_choosen, max(0.01, min(sum_bone_pos, fBonesize)),max(0.01, round((min(sum_bone_pos, fBonesize))*100)/100)))
if not bReorientBones:
new_bone_size = bone_size_choosen
#==================================================================================================
# Skeleton. Build.
if psk_bone_name_toolong:
print('Warning. Some bones will be renamed(names are too long). Animation import may be broken.')
for psk_bone in psk_bones:
# TODO too long name cutting options?
orig_long_name = psk_bone.name
# Blender will cut the name here (>63 chars)
edit_bone = armature_obj.data.edit_bones.new(psk_bone.name)
edit_bone["orig_long_name"] = orig_long_name
# if orig_long_name != edit_bone.name:
# print('--')
# print(len(orig_long_name),orig_long_name)
# print(len(edit_bone.name),edit_bone.name)
# Use the bone name made by blender (.001 , .002 etc.)
psk_bone.name = edit_bone.name
else:
for psk_bone in psk_bones:
edit_bone = armature_obj.data.edit_bones.new(psk_bone.name)
psk_bone.name = edit_bone.name
for psk_bone in psk_bones:
edit_bone = armature_obj.data.edit_bones[psk_bone.name]
armature_obj.data.edit_bones.active = edit_bone
if psk_bone.parent is not None:
edit_bone.parent = armature_obj.data.edit_bones[psk_bone.parent.name]
else:
if bDontInvertRoot:
psk_bone.orig_quat.conjugate()
if bReorientBones:
(new_bone_size, quat_orient_diff) = calc_bone_rotation(psk_bone, bone_size_choosen, bReorientDirectly, sum_bone_pos)
# @
# post_quat = psk_bone.orig_quat.conjugated() * quat_orient_diff
post_quat = quat_orient_diff
post_quat.rotate( psk_bone.orig_quat.conjugated() )
else:
post_quat = psk_bone.orig_quat.conjugated()
# only length of this vector is matter?
edit_bone.tail = Vector(( 0.0, new_bone_size, 0.0))
# @
# edit_bone.matrix = psk_bone.mat_world * post_quat.to_matrix().to_4x4()
m = post_quat.copy()
m.rotate( psk_bone.mat_world )
m = m.to_matrix().to_4x4()
m.translation = psk_bone.mat_world.translation
edit_bone.matrix = m
# some dev code...
#### FINAL
# post_quat = psk_bone.orig_quat.conjugated() * quat_diff
# edit_bone.matrix = psk_bone.mat_world * test_quat.to_matrix().to_4x4()
# edit_bone["post_quat"] = test_quat
####
# edit_bone["post_quat"] = Quaternion((1,0,0,0))
# edit_bone.matrix = psk_bone.mat_world* psk_bone.rot
# if edit_bone.parent:
# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (psk_bone.orig_quat.conjugated().to_matrix().to_4x4())
# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (test_quat.to_matrix().to_4x4())
# else:
# edit_bone.matrix = psk_bone.orig_quat.to_matrix().to_4x4()
# save bindPose information for .psa import
# dev
edit_bone["orig_quat"] = psk_bone.orig_quat
edit_bone["orig_loc"] = psk_bone.orig_loc
edit_bone["post_quat"] = post_quat
'''
bone = edit_bone
if psk_bone.parent is not None:
orig_loc = bone.matrix.translation - bone.parent.matrix.translation
orig_loc.rotate( bone.parent.matrix.to_quaternion().conjugated() )
orig_quat = bone.matrix.to_quaternion()
orig_quat.rotate( bone.parent.matrix.to_quaternion().conjugated() )
orig_quat.conjugate()
if orig_quat.dot( psk_bone.orig_quat ) < 0.95:
print(bone.name, psk_bone.orig_quat, orig_quat, orig_quat.dot( psk_bone.orig_quat ))
print('parent:', bone.parent.matrix.to_quaternion(), bone.parent.matrix.to_quaternion().rotation_difference(bone.matrix.to_quaternion()) )
if (psk_bone.orig_loc - orig_loc).length > 0.02:
print(bone.name, psk_bone.orig_loc, orig_loc, (psk_bone.orig_loc - orig_loc).length)
'''
utils_set_mode('OBJECT')
#==================================================================================================
# Weights
if bImportmesh:
vertices_total = len(Vertices)
for ( _, PointIndex, BoneIndex ) in Weights:
if PointIndex < vertices_total: # can it be not?
psk_bones[BoneIndex].have_weight_data = True
# else:
# print(psk_bones[BoneIndex].name, 'for other mesh',PointIndex ,vertices_total)
#print("weight:", PointIndex, BoneIndex, Weight)
# Weights.append(None)
# print(Weights.count(None))
# Original vertex colorization code
'''
# Weights.sort( key = lambda wgh: wgh[0])
if bImportmesh:
VtxCol = []
bones_count = len(psk_bones)
for x in range(bones_count):
#change the overall darkness of each material in a range between 0.1 and 0.9
tmpVal = ((float(x) + 1.0) / bones_count * 0.7) + 0.1
tmpVal = int(tmpVal * 256)
tmpCol = [tmpVal, tmpVal, tmpVal, 0]
#Change the color of each material slightly
if x % 3 == 0:
if tmpCol[0] < 128:
tmpCol[0] += 60
else:
tmpCol[0] -= 60
if x % 3 == 1:
if tmpCol[1] < 128:
tmpCol[1] += 60
else:
tmpCol[1] -= 60
if x % 3 == 2:
if tmpCol[2] < 128:
tmpCol[2] += 60
else:
tmpCol[2] -= 60
#Add the material to the mesh
VtxCol.append(tmpCol)
for x in range(len(Tmsh.faces)):
for y in range(len(Tmsh.faces[x].v)):
#find v in Weights[n][0]
findVal = Tmsh.faces[x].v[y].index
n = 0
while findVal != Weights[n][0]:
n = n + 1
TmpCol = VtxCol[Weights[n][1]]
#check if a vertex has more than one influence
if n != len(Weights) - 1:
if Weights[n][0] == Weights[n + 1][0]:
#if there is more than one influence, use the one with the greater influence
#for simplicity only 2 influences are checked, 2nd and 3rd influences are usually very small
if Weights[n][2] < Weights[n + 1][2]:
TmpCol = VtxCol[Weights[n + 1][1]]
Tmsh.faces[x].col.append(NMesh.Col(TmpCol[0], TmpCol[1], TmpCol[2], 0))
'''
#===================================================================================================
# UV. Setup.
if bImportmesh:
# Trick! Create UV maps BEFORE mesh and get (0,0) coordinates for free!
# ...otherwise UV coords will be copied from active, or calculated from mesh...
if bSpltiUVdata:
for i in range(len(uv_mat_ids)):
get_uv_layers(mesh_data).new(name = NAME_UV_PREFIX + str(i))
else:
get_uv_layers(mesh_data).new(name = NAME_UV_PREFIX+"_SINGLE")
for counter, uv_data in enumerate(Extrauvs):
if len(mesh_data.uv_layers) < MAX_UVS:
get_uv_layers(mesh_data).new(name = "EXTRAUVS"+str(counter))
else:
Extrauvs.remove(uv_data)
print('Extra UV layer %s is ignored. Re-import without "Split UV data".' % counter)
#==================================================================================================
# Mesh. Build.
mesh_data.from_pydata(Vertices,[],Faces)
#==================================================================================================
# Vertex Normal. Set.
if Normals is not None:
mesh_data.polygons.foreach_set("use_smooth", [True] * len(mesh_data.polygons))
mesh_data.normals_split_custom_set_from_vertices(Normals)
mesh_data.use_auto_smooth = True
#===================================================================================================
# UV. Set.
if bImportmesh:
for face in mesh_data.polygons:
face.material_index = UV_by_face[face.index][1]
uv_layers = mesh_data.uv_layers
if not bSpltiUVdata:
uvLayer = uv_layers[0]
# per face
# for faceIdx, (faceUVs, faceMatIdx, _, _, wmidx) in enumerate(UV_by_face):
for faceIdx, (faceUVs, faceMatIdx, WedgeMatIds) in enumerate(UV_by_face):
# per vertex
for vertN, uv in enumerate(faceUVs):
loopId = faceIdx * 3 + vertN
if bSpltiUVdata:
uvLayer = uv_layers[WedgeMatIds[vertN]]
uvLayer.data[loopId].uv = uv
#==================================================================================================
# VertexColors
if VertexColors is not None:
vtx_color_layer = mesh_data.vertex_colors.new(name = "PSKVTXCOL_0", do_init = False)
pervertex = [None] * len(Vertices)
for counter, (vertexid,_,_,_) in enumerate(Wedges):
# Is it possible ?
if (pervertex[vertexid] is not None) and (pervertex[vertexid] != VertexColors[counter]):
print('Not equal vertex colors. ', vertexid, pervertex[vertexid], VertexColors[counter])
pervertex[vertexid] = VertexColors[counter]
for counter, loop in enumerate(mesh_data.loops):
color = pervertex[ loop.vertex_index ]
if color is None:
vtx_color_layer.data[ counter ].color = (1.,1.,1.,1.)
else:
if bToSRGB:
vtx_color_layer.data[ counter ].color = (
color_linear_to_srgb(color[0] / 255),
color_linear_to_srgb(color[1] / 255),
color_linear_to_srgb(color[2] / 255),
color[3] / 255
)
else:
vtx_color_layer.data[ counter ].color = (
color[0] / 255,
color[1] / 255,
color[2] / 255,
color[3] / 255
)
#===================================================================================================
# Extra UVs. Set.
# for counter, uv_data in enumerate(Extrauvs):
# uvLayer = mesh_data.uv_layers[ counter - len(Extrauvs) ]
# for uv_index, uv_coords in enumerate(uv_data):
# uvLayer.data[uv_index].uv = (uv_coords[0], 1.0 - uv_coords[1])
for counter, uv_data in enumerate(Extrauvs):
uvLayer = mesh_data.uv_layers[ counter - len(Extrauvs) ]
for faceIdx, (WedgeIdx3,WedgeIdx2,WedgeIdx1) in enumerate(WedgeIdx_by_faceIdx):
# equal to gltf
uvLayer.data[faceIdx*3 ].uv = (uv_data[WedgeIdx2][0], 1.0 - uv_data[WedgeIdx2][1])
uvLayer.data[faceIdx*3+1].uv = (uv_data[WedgeIdx1][0], 1.0 - uv_data[WedgeIdx1][1])
uvLayer.data[faceIdx*3+2].uv = (uv_data[WedgeIdx3][0], 1.0 - uv_data[WedgeIdx3][1])
# uvLayer.data[faceIdx*3 ].uv = (uv_data[WedgeIdx3][0], 1.0 - uv_data[WedgeIdx3][1])
# uvLayer.data[faceIdx*3+1].uv = (uv_data[WedgeIdx2][0], 1.0 - uv_data[WedgeIdx2][1])
# uvLayer.data[faceIdx*3+2].uv = (uv_data[WedgeIdx1][0], 1.0 - uv_data[WedgeIdx1][1])
#===================================================================================================
# Mesh. Vertex Groups. Bone Weights.
for psk_bone in psk_bones:
if psk_bone.have_weight_data:
psk_bone.vertex_group = mesh_obj.vertex_groups.new(name = psk_bone.name)
# else:
# print(psk_bone.name, 'have no influence on this mesh')
for weight, vertex_id, bone_index_w in filter(None, Weights):
psk_bones[bone_index_w].vertex_group.add((vertex_id,), weight, 'ADD')
#===================================================================================================
# Skeleton. Colorize.
if bImportbone:
bone_group_unused = armature_obj.pose.bone_groups.new(name = "Unused bones")
bone_group_unused.color_set = 'THEME14'
bone_group_nochild = armature_obj.pose.bone_groups.new(name = "No children")
bone_group_nochild.color_set = 'THEME03'
armature_data.show_group_colors = True
for psk_bone in psk_bones:
pose_bone = armature_obj.pose.bones[psk_bone.name]
if psk_bone.have_weight_data:
if len(psk_bone.children) == 0:
pose_bone.bone_group = bone_group_nochild
else:
pose_bone.bone_group = bone_group_unused
#===================================================================================================
# Final
if bImportmesh:
util_obj_link(context, mesh_obj)
util_select_all(False)
if not bImportbone:
util_obj_select(context, mesh_obj)
util_obj_set_active(context, mesh_obj)
else:
# select_all(False)
util_obj_select(context, armature_obj)
# parenting mesh to armature object
mesh_obj.parent = armature_obj
mesh_obj.parent_type = 'OBJECT'
# add armature modifier
blender_modifier = mesh_obj.modifiers.new( armature_obj.data.name, type = 'ARMATURE')
blender_modifier.show_expanded = False
blender_modifier.use_vertex_groups = True
blender_modifier.use_bone_envelopes = False
blender_modifier.object = armature_obj
# utils_set_mode('OBJECT')
# select_all(False)
util_obj_select(context, armature_obj)
util_obj_set_active(context, armature_obj)
# print("Done: %f sec." % (time.process_time() - ref_time))
utils_set_mode('OBJECT')
return True | [
"def",
"pskimport",
"(",
"filepath",
",",
"context",
"=",
"None",
",",
"bImportmesh",
"=",
"True",
",",
"bImportbone",
"=",
"True",
",",
"bSpltiUVdata",
"=",
"False",
",",
"fBonesize",
"=",
"5.0",
",",
"fBonesizeRatio",
"=",
"0.6",
",",
"bDontInvertRoot",
"=",
"True",
",",
"bReorientBones",
"=",
"False",
",",
"bReorientDirectly",
"=",
"False",
",",
"bScaleDown",
"=",
"True",
",",
"bToSRGB",
"=",
"True",
",",
"error_callback",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"error_callback",
",",
"'__call__'",
")",
":",
"# error_callback = __pass",
"error_callback",
"=",
"print",
"# ref_time = time.process_time()",
"if",
"not",
"bImportbone",
"and",
"not",
"bImportmesh",
":",
"error_callback",
"(",
"\"Nothing to do.\\nSet something for import.\"",
")",
"return",
"False",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"print",
"(",
"\"---------EXECUTING PSK PYTHON IMPORTER---------\"",
")",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"#file may not exist",
"try",
":",
"file",
"=",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"except",
"IOError",
":",
"error_callback",
"(",
"'Error while opening file for reading:\\n \"'",
"+",
"filepath",
"+",
"'\"'",
")",
"return",
"False",
"if",
"not",
"util_check_file_header",
"(",
"file",
",",
"'psk'",
")",
":",
"error_callback",
"(",
"'Not psk file:\\n \"'",
"+",
"filepath",
"+",
"'\"'",
")",
"return",
"False",
"Vertices",
"=",
"None",
"Wedges",
"=",
"None",
"Faces",
"=",
"None",
"UV_by_face",
"=",
"None",
"Materials",
"=",
"None",
"Bones",
"=",
"None",
"Weights",
"=",
"None",
"VertexColors",
"=",
"None",
"Extrauvs",
"=",
"[",
"]",
"Normals",
"=",
"None",
"WedgeIdx_by_faceIdx",
"=",
"None",
"if",
"not",
"context",
":",
"context",
"=",
"bpy",
".",
"context",
"#================================================================================================== ",
"# Materials MaterialNameRaw | TextureIndex | PolyFlags | AuxMaterial | AuxFlags | LodBias | LodStyle ",
"# Only Name is usable.",
"def",
"read_materials",
"(",
")",
":",
"nonlocal",
"Materials",
"Materials",
"=",
"[",
"]",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"MaterialNameRaw",
",",
")",
"=",
"unpack_from",
"(",
"'64s24x'",
",",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"Materials",
".",
"append",
"(",
"util_bytes_to_str",
"(",
"MaterialNameRaw",
")",
")",
"#================================================================================================== ",
"# Faces WdgIdx1 | WdgIdx2 | WdgIdx3 | MatIdx | AuxMatIdx | SmthGrp",
"def",
"read_faces",
"(",
")",
":",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"nonlocal",
"Faces",
",",
"UV_by_face",
",",
"WedgeIdx_by_faceIdx",
"UV_by_face",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"Faces",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"WedgeIdx_by_faceIdx",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"if",
"len",
"(",
"Wedges",
")",
">",
"65536",
":",
"unpack_format",
"=",
"'=IIIBBI'",
"else",
":",
"unpack_format",
"=",
"'=HHHBBI'",
"unpack_data",
"=",
"Struct",
"(",
"unpack_format",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"WdgIdx1",
",",
"WdgIdx2",
",",
"WdgIdx3",
",",
"MatIndex",
",",
"AuxMatIndex",
",",
"#unused",
"SmoothingGroup",
"# Umodel is not exporting SmoothingGroups",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"# looks ugly",
"# Wedges is (point_index, u, v, MatIdx)",
"(",
"(",
"vertid0",
",",
"u0",
",",
"v0",
",",
"matid0",
")",
",",
"(",
"vertid1",
",",
"u1",
",",
"v1",
",",
"matid1",
")",
",",
"(",
"vertid2",
",",
"u2",
",",
"v2",
",",
"matid2",
")",
")",
"=",
"Wedges",
"[",
"WdgIdx1",
"]",
",",
"Wedges",
"[",
"WdgIdx2",
"]",
",",
"Wedges",
"[",
"WdgIdx3",
"]",
"# note order: C,B,A",
"# Faces[counter] = (vertid2, vertid1, vertid0)",
"Faces",
"[",
"counter",
"]",
"=",
"(",
"vertid1",
",",
"vertid0",
",",
"vertid2",
")",
"# Faces[counter] = (vertid1, vertid2, vertid0)",
"# Faces[counter] = (vertid0, vertid1, vertid2)",
"# uv = ( ( u2, 1.0 - v2 ), ( u1, 1.0 - v1 ), ( u0, 1.0 - v0 ) )",
"uv",
"=",
"(",
"(",
"u1",
",",
"1.0",
"-",
"v1",
")",
",",
"(",
"u0",
",",
"1.0",
"-",
"v0",
")",
",",
"(",
"u2",
",",
"1.0",
"-",
"v2",
")",
")",
"# Mapping: FaceIndex <=> UV data <=> FaceMatIndex",
"UV_by_face",
"[",
"counter",
"]",
"=",
"(",
"uv",
",",
"MatIndex",
",",
"(",
"matid2",
",",
"matid1",
",",
"matid0",
")",
")",
"# We need this for EXTRA UVs",
"WedgeIdx_by_faceIdx",
"[",
"counter",
"]",
"=",
"(",
"WdgIdx3",
",",
"WdgIdx2",
",",
"WdgIdx1",
")",
"#==================================================================================================",
"# Vertices X | Y | Z",
"def",
"read_vertices",
"(",
")",
":",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"nonlocal",
"Vertices",
"Vertices",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'3f'",
")",
".",
"unpack_from",
"if",
"bScaleDown",
":",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"vec_x",
",",
"vec_y",
",",
"vec_z",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"Vertices",
"[",
"counter",
"]",
"=",
"(",
"vec_x",
"*",
"0.01",
",",
"vec_y",
"*",
"0.01",
",",
"vec_z",
"*",
"0.01",
")",
"# equal to gltf",
"# Vertices[counter] = (vec_x*0.01, vec_z*0.01, -vec_y*0.01)",
"else",
":",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"Vertices",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"#================================================================================================== ",
"# Wedges (UV) VertexId | U | V | MatIdx ",
"def",
"read_wedges",
"(",
")",
":",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"nonlocal",
"Wedges",
"Wedges",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'=IffBxxx'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"vertex_id",
",",
"u",
",",
"v",
",",
"material_index",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"# print(vertex_id, u, v, material_index)",
"# Wedges[counter] = (vertex_id, u, v, material_index)",
"Wedges",
"[",
"counter",
"]",
"=",
"[",
"vertex_id",
",",
"u",
",",
"v",
",",
"material_index",
"]",
"#================================================================================================== ",
"# Bones (VBone .. VJointPos ) Name|Flgs|NumChld|PrntIdx|Qw|Qx|Qy|Qz|LocX|LocY|LocZ|Lngth|XSize|YSize|ZSize",
"def",
"read_bones",
"(",
")",
":",
"nonlocal",
"Bones",
",",
"bImportbone",
"if",
"chunk_datacount",
"==",
"0",
":",
"bImportbone",
"=",
"False",
"if",
"bImportbone",
":",
"# unpack_data = Struct('64s3i11f').unpack_from",
"unpack_data",
"=",
"Struct",
"(",
"'64s3i7f16x'",
")",
".",
"unpack_from",
"else",
":",
"unpack_data",
"=",
"Struct",
"(",
"'64s56x'",
")",
".",
"unpack_from",
"Bones",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"Bones",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"#================================================================================================== ",
"# Influences (Bone Weight) (VRawBoneInfluence) ( Weight | PntIdx | BoneIdx)",
"def",
"read_weights",
"(",
")",
":",
"nonlocal",
"Weights",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"Weights",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'fii'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"Weights",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"#================================================================================================== ",
"# Vertex colors. R G B A bytes. NOTE: it is Wedge color.(uses Wedges index)",
"def",
"read_vertex_colors",
"(",
")",
":",
"nonlocal",
"VertexColors",
"unpack_data",
"=",
"Struct",
"(",
"\"=4B\"",
")",
".",
"unpack_from",
"VertexColors",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"VertexColors",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"#================================================================================================== ",
"# Extra UV. U | V",
"def",
"read_extrauvs",
"(",
")",
":",
"unpack_data",
"=",
"Struct",
"(",
"\"=2f\"",
")",
".",
"unpack_from",
"uvdata",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"uvdata",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"Extrauvs",
".",
"append",
"(",
"uvdata",
")",
"#==================================================================================================",
"# Vertex Normals NX | NY | NZ",
"def",
"read_normals",
"(",
")",
":",
"if",
"not",
"bImportmesh",
":",
"return",
"True",
"nonlocal",
"Normals",
"Normals",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'3f'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"Normals",
"[",
"counter",
"]",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"counter",
"*",
"chunk_datasize",
")",
"CHUNKS_HANDLERS",
"=",
"{",
"'PNTS0000'",
":",
"read_vertices",
",",
"'VTXW0000'",
":",
"read_wedges",
",",
"'VTXW3200'",
":",
"read_wedges",
",",
"#?",
"'FACE0000'",
":",
"read_faces",
",",
"'FACE3200'",
":",
"read_faces",
",",
"'MATT0000'",
":",
"read_materials",
",",
"'REFSKELT'",
":",
"read_bones",
",",
"'REFSKEL0'",
":",
"read_bones",
",",
"#?",
"'RAWW0000'",
":",
"read_weights",
",",
"'RAWWEIGH'",
":",
"read_weights",
",",
"'VERTEXCO'",
":",
"read_vertex_colors",
",",
"# VERTEXCOLOR",
"'EXTRAUVS'",
":",
"read_extrauvs",
",",
"'VTXNORMS'",
":",
"read_normals",
"}",
"#===================================================================================================",
"# File. Read all needed data.",
"# VChunkHeader Struct",
"# ChunkID|TypeFlag|DataSize|DataCount",
"# 0 |1 |2 |3",
"while",
"True",
":",
"header_bytes",
"=",
"file",
".",
"read",
"(",
"32",
")",
"if",
"len",
"(",
"header_bytes",
")",
"<",
"32",
":",
"if",
"len",
"(",
"header_bytes",
")",
"!=",
"0",
":",
"error_callback",
"(",
"\"Unexpected end of file.(%s/32 bytes)\"",
"%",
"len",
"(",
"header_bytes",
")",
")",
"break",
"(",
"chunk_id",
",",
"chunk_type",
",",
"chunk_datasize",
",",
"chunk_datacount",
")",
"=",
"unpack",
"(",
"'20s3i'",
",",
"header_bytes",
")",
"chunk_id_str",
"=",
"util_bytes_to_str",
"(",
"chunk_id",
")",
"chunk_id_str",
"=",
"chunk_id_str",
"[",
":",
"8",
"]",
"if",
"chunk_id_str",
"in",
"CHUNKS_HANDLERS",
":",
"chunk_data",
"=",
"file",
".",
"read",
"(",
"chunk_datasize",
"*",
"chunk_datacount",
")",
"if",
"len",
"(",
"chunk_data",
")",
"<",
"chunk_datasize",
"*",
"chunk_datacount",
":",
"error_callback",
"(",
"'Psk chunk %s is broken.'",
"%",
"chunk_id_str",
")",
"return",
"False",
"CHUNKS_HANDLERS",
"[",
"chunk_id_str",
"]",
"(",
")",
"else",
":",
"print",
"(",
"'Unknown chunk: '",
",",
"chunk_id_str",
")",
"file",
".",
"seek",
"(",
"chunk_datasize",
"*",
"chunk_datacount",
",",
"1",
")",
"# print(chunk_id_str, chunk_datacount)",
"file",
".",
"close",
"(",
")",
"print",
"(",
"\" Importing file:\"",
",",
"filepath",
")",
"if",
"not",
"bImportmesh",
"and",
"(",
"Bones",
"is",
"None",
"or",
"len",
"(",
"Bones",
")",
"==",
"0",
")",
":",
"error_callback",
"(",
"\"Psk: no skeleton data.\"",
")",
"return",
"False",
"MAX_UVS",
"=",
"8",
"NAME_UV_PREFIX",
"=",
"\"UV\"",
"# file name w/out extension",
"gen_name_part",
"=",
"util_gen_name_part",
"(",
"filepath",
")",
"gen_names",
"=",
"{",
"'armature_object'",
":",
"gen_name_part",
"+",
"'.ao'",
",",
"'armature_data'",
":",
"gen_name_part",
"+",
"'.ad'",
",",
"'mesh_object'",
":",
"gen_name_part",
"+",
"'.mo'",
",",
"'mesh_data'",
":",
"gen_name_part",
"+",
"'.md'",
"}",
"if",
"bImportmesh",
":",
"mesh_data",
"=",
"bpy",
".",
"data",
".",
"meshes",
".",
"new",
"(",
"gen_names",
"[",
"'mesh_data'",
"]",
")",
"mesh_obj",
"=",
"bpy",
".",
"data",
".",
"objects",
".",
"new",
"(",
"gen_names",
"[",
"'mesh_object'",
"]",
",",
"mesh_data",
")",
"#==================================================================================================",
"# UV. Prepare",
"if",
"bImportmesh",
":",
"if",
"bSpltiUVdata",
":",
"# store how much each \"matrial index\" have vertices",
"uv_mat_ids",
"=",
"{",
"}",
"for",
"(",
"_",
",",
"_",
",",
"_",
",",
"material_index",
")",
"in",
"Wedges",
":",
"if",
"not",
"(",
"material_index",
"in",
"uv_mat_ids",
")",
":",
"uv_mat_ids",
"[",
"material_index",
"]",
"=",
"1",
"else",
":",
"uv_mat_ids",
"[",
"material_index",
"]",
"+=",
"1",
"# if we have more UV material indexes than blender UV maps, then...",
"if",
"bSpltiUVdata",
"and",
"len",
"(",
"uv_mat_ids",
")",
">",
"MAX_UVS",
":",
"uv_mat_ids_len",
"=",
"len",
"(",
"uv_mat_ids",
")",
"print",
"(",
"'UVs: %s out of %s is combined in a first UV map(%s0)'",
"%",
"(",
"uv_mat_ids_len",
"-",
"8",
",",
"uv_mat_ids_len",
",",
"NAME_UV_PREFIX",
")",
")",
"mat_idx_proxy",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"uv_mat_ids",
")",
"counts_sorted",
"=",
"sorted",
"(",
"uv_mat_ids",
".",
"values",
"(",
")",
",",
"reverse",
"=",
"True",
")",
"new_mat_index",
"=",
"MAX_UVS",
"-",
"1",
"for",
"c",
"in",
"counts_sorted",
":",
"for",
"mat_idx",
",",
"counts",
"in",
"uv_mat_ids",
".",
"items",
"(",
")",
":",
"if",
"c",
"==",
"counts",
":",
"mat_idx_proxy",
"[",
"mat_idx",
"]",
"=",
"new_mat_index",
"if",
"new_mat_index",
">",
"0",
":",
"new_mat_index",
"-=",
"1",
"# print('MatIdx remap: %s > %s' % (mat_idx,new_mat_index))",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"Wedges",
")",
")",
":",
"Wedges",
"[",
"i",
"]",
"[",
"3",
"]",
"=",
"mat_idx_proxy",
"[",
"Wedges",
"[",
"i",
"]",
"[",
"3",
"]",
"]",
"# print('Wedges:', chunk_datacount)",
"# print('uv_mat_ids', uv_mat_ids)",
"# print('uv_mat_ids', uv_mat_ids)",
"# for w in Wedges:",
"if",
"bImportmesh",
":",
"# print(\"-- Materials -- (index, name, faces)\")",
"blen_materials",
"=",
"[",
"]",
"for",
"materialname",
"in",
"Materials",
":",
"matdata",
"=",
"bpy",
".",
"data",
".",
"materials",
".",
"get",
"(",
"materialname",
")",
"if",
"matdata",
"is",
"None",
":",
"matdata",
"=",
"bpy",
".",
"data",
".",
"materials",
".",
"new",
"(",
"materialname",
")",
"# matdata = bpy.data.materials.new( materialname )",
"blen_materials",
".",
"append",
"(",
"matdata",
")",
"mesh_data",
".",
"materials",
".",
"append",
"(",
"matdata",
")",
"# print(counter,materialname,TextureIndex)",
"# if mat_groups.get(counter) is not None:",
"# print(\"%i: %s\" % (counter, materialname), len(mat_groups[counter]))",
"#==================================================================================================",
"# Prepare bone data",
"def",
"init_psk_bone",
"(",
"i",
",",
"psk_bones",
",",
"name_raw",
")",
":",
"psk_bone",
"=",
"class_psk_bone",
"(",
")",
"psk_bone",
".",
"children",
"=",
"[",
"]",
"psk_bone",
".",
"name",
"=",
"util_bytes_to_str",
"(",
"name_raw",
")",
"psk_bones",
"[",
"i",
"]",
"=",
"psk_bone",
"return",
"psk_bone",
"psk_bone_name_toolong",
"=",
"False",
"# indexed by bone index. array of psk_bone",
"psk_bones",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"Bones",
")",
"if",
"not",
"bImportbone",
":",
"#data needed for mesh-only import",
"for",
"counter",
",",
"(",
"name_raw",
",",
")",
"in",
"enumerate",
"(",
"Bones",
")",
":",
"init_psk_bone",
"(",
"counter",
",",
"psk_bones",
",",
"name_raw",
")",
"if",
"bImportbone",
":",
"#else?",
"# average bone length",
"sum_bone_pos",
"=",
"0",
"for",
"counter",
",",
"(",
"name_raw",
",",
"flags",
",",
"NumChildren",
",",
"ParentIndex",
",",
"#0 1 2 3",
"quat_x",
",",
"quat_y",
",",
"quat_z",
",",
"quat_w",
",",
"#4 5 6 7",
"vec_x",
",",
"vec_y",
",",
"vec_z",
"# , #8 9 10",
"# joint_length, #11",
"# scale_x, scale_y, scale_z",
")",
"in",
"enumerate",
"(",
"Bones",
")",
":",
"psk_bone",
"=",
"init_psk_bone",
"(",
"counter",
",",
"psk_bones",
",",
"name_raw",
")",
"psk_bone",
".",
"bone_index",
"=",
"counter",
"psk_bone",
".",
"parent_index",
"=",
"ParentIndex",
"# Tested. 64 is getting cut to 63",
"if",
"len",
"(",
"psk_bone",
".",
"name",
")",
">",
"63",
":",
"psk_bone_name_toolong",
"=",
"True",
"# print('Warning. Bone name is too long:', psk_bone.name)",
"# make sure we have valid parent_index",
"if",
"psk_bone",
".",
"parent_index",
"<",
"0",
":",
"psk_bone",
".",
"parent_index",
"=",
"0",
"# psk_bone.scale = (scale_x, scale_y, scale_z)",
"# print(\"%s: %03f %03f | %f\" % (psk_bone.name, scale_x, scale_y, joint_length),scale_x)",
"# print(\"%s:\" % (psk_bone.name), vec_x, quat_x)",
"# store bind pose to make it available for psa-import via CustomProperty of the Blender bone",
"psk_bone",
".",
"orig_quat",
"=",
"Quaternion",
"(",
"(",
"quat_w",
",",
"quat_x",
",",
"quat_y",
",",
"quat_z",
")",
")",
"if",
"bScaleDown",
":",
"psk_bone",
".",
"orig_loc",
"=",
"Vector",
"(",
"(",
"vec_x",
"*",
"0.01",
",",
"vec_y",
"*",
"0.01",
",",
"vec_z",
"*",
"0.01",
")",
")",
"else",
":",
"psk_bone",
".",
"orig_loc",
"=",
"Vector",
"(",
"(",
"vec_x",
",",
"vec_y",
",",
"vec_z",
")",
")",
"# root bone must have parent_index = 0 and selfindex = 0",
"if",
"psk_bone",
".",
"parent_index",
"==",
"0",
"and",
"psk_bone",
".",
"bone_index",
"==",
"psk_bone",
".",
"parent_index",
":",
"if",
"bDontInvertRoot",
":",
"psk_bone",
".",
"mat_world_rot",
"=",
"psk_bone",
".",
"orig_quat",
".",
"to_matrix",
"(",
")",
"else",
":",
"psk_bone",
".",
"mat_world_rot",
"=",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
".",
"to_matrix",
"(",
")",
"psk_bone",
".",
"mat_world",
"=",
"Matrix",
".",
"Translation",
"(",
"psk_bone",
".",
"orig_loc",
")",
"sum_bone_pos",
"+=",
"psk_bone",
".",
"orig_loc",
".",
"length",
"#==================================================================================================",
"# Bones. Calc World-space matrix",
"# TODO optimize math.",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"if",
"psk_bone",
".",
"parent_index",
"==",
"0",
":",
"if",
"psk_bone",
".",
"bone_index",
"==",
"0",
":",
"psk_bone",
".",
"parent",
"=",
"None",
"continue",
"parent",
"=",
"psk_bones",
"[",
"psk_bone",
".",
"parent_index",
"]",
"psk_bone",
".",
"parent",
"=",
"parent",
"parent",
".",
"children",
".",
"append",
"(",
"psk_bone",
")",
"# mat_world - world space bone matrix WITHOUT own rotation",
"# mat_world_rot - world space bone rotation WITH own rotation",
"# psk_bone.mat_world = parent.mat_world_rot.to_4x4()",
"# psk_bone.mat_world.translation = parent.mat_world.translation + parent.mat_world_rot * psk_bone.orig_loc",
"# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()",
"psk_bone",
".",
"mat_world",
"=",
"parent",
".",
"mat_world_rot",
".",
"to_4x4",
"(",
")",
"v",
"=",
"psk_bone",
".",
"orig_loc",
".",
"copy",
"(",
")",
"v",
".",
"rotate",
"(",
"parent",
".",
"mat_world_rot",
")",
"psk_bone",
".",
"mat_world",
".",
"translation",
"=",
"parent",
".",
"mat_world",
".",
"translation",
"+",
"v",
"psk_bone",
".",
"mat_world_rot",
"=",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
".",
"to_matrix",
"(",
")",
"psk_bone",
".",
"mat_world_rot",
".",
"rotate",
"(",
"parent",
".",
"mat_world_rot",
")",
"# psk_bone.mat_world = ( parent.mat_world_rot.to_4x4() * psk_bone.trans)",
"# psk_bone.mat_world.translation += parent.mat_world.translation",
"# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()",
"#==================================================================================================",
"# Skeleton. Prepare.",
"armature_data",
"=",
"bpy",
".",
"data",
".",
"armatures",
".",
"new",
"(",
"gen_names",
"[",
"'armature_data'",
"]",
")",
"armature_obj",
"=",
"bpy",
".",
"data",
".",
"objects",
".",
"new",
"(",
"gen_names",
"[",
"'armature_object'",
"]",
",",
"armature_data",
")",
"# TODO: options for axes and x_ray?",
"armature_data",
".",
"show_axes",
"=",
"False",
"armature_data",
".",
"display_type",
"=",
"'STICK'",
"armature_obj",
".",
"show_in_front",
"=",
"True",
"util_obj_link",
"(",
"context",
",",
"armature_obj",
")",
"util_select_all",
"(",
"False",
")",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")",
"utils_set_mode",
"(",
"'EDIT'",
")",
"sum_bone_pos",
"/=",
"len",
"(",
"Bones",
")",
"# average",
"sum_bone_pos",
"*=",
"fBonesizeRatio",
"# corrected",
"# bone_size_choosen = max(0.01, round((min(sum_bone_pos, fBonesize))))",
"bone_size_choosen",
"=",
"max",
"(",
"0.01",
",",
"round",
"(",
"(",
"min",
"(",
"sum_bone_pos",
",",
"fBonesize",
")",
")",
"*",
"100",
")",
"/",
"100",
")",
"# bone_size_choosen = max(0.01, min(sum_bone_pos, fBonesize))",
"# print(\"Bonesize %f | old: %f round: %f\" % (bone_size_choosen, max(0.01, min(sum_bone_pos, fBonesize)),max(0.01, round((min(sum_bone_pos, fBonesize))*100)/100)))",
"if",
"not",
"bReorientBones",
":",
"new_bone_size",
"=",
"bone_size_choosen",
"#==================================================================================================",
"# Skeleton. Build.",
"if",
"psk_bone_name_toolong",
":",
"print",
"(",
"'Warning. Some bones will be renamed(names are too long). Animation import may be broken.'",
")",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"# TODO too long name cutting options?",
"orig_long_name",
"=",
"psk_bone",
".",
"name",
"# Blender will cut the name here (>63 chars)",
"edit_bone",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
".",
"new",
"(",
"psk_bone",
".",
"name",
")",
"edit_bone",
"[",
"\"orig_long_name\"",
"]",
"=",
"orig_long_name",
"# if orig_long_name != edit_bone.name:",
"# print('--')",
"# print(len(orig_long_name),orig_long_name)",
"# print(len(edit_bone.name),edit_bone.name)",
"# Use the bone name made by blender (.001 , .002 etc.)",
"psk_bone",
".",
"name",
"=",
"edit_bone",
".",
"name",
"else",
":",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"edit_bone",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
".",
"new",
"(",
"psk_bone",
".",
"name",
")",
"psk_bone",
".",
"name",
"=",
"edit_bone",
".",
"name",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"edit_bone",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
"[",
"psk_bone",
".",
"name",
"]",
"armature_obj",
".",
"data",
".",
"edit_bones",
".",
"active",
"=",
"edit_bone",
"if",
"psk_bone",
".",
"parent",
"is",
"not",
"None",
":",
"edit_bone",
".",
"parent",
"=",
"armature_obj",
".",
"data",
".",
"edit_bones",
"[",
"psk_bone",
".",
"parent",
".",
"name",
"]",
"else",
":",
"if",
"bDontInvertRoot",
":",
"psk_bone",
".",
"orig_quat",
".",
"conjugate",
"(",
")",
"if",
"bReorientBones",
":",
"(",
"new_bone_size",
",",
"quat_orient_diff",
")",
"=",
"calc_bone_rotation",
"(",
"psk_bone",
",",
"bone_size_choosen",
",",
"bReorientDirectly",
",",
"sum_bone_pos",
")",
"# @",
"# post_quat = psk_bone.orig_quat.conjugated() * quat_orient_diff",
"post_quat",
"=",
"quat_orient_diff",
"post_quat",
".",
"rotate",
"(",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
")",
"else",
":",
"post_quat",
"=",
"psk_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
"# only length of this vector is matter?",
"edit_bone",
".",
"tail",
"=",
"Vector",
"(",
"(",
"0.0",
",",
"new_bone_size",
",",
"0.0",
")",
")",
"# @",
"# edit_bone.matrix = psk_bone.mat_world * post_quat.to_matrix().to_4x4()",
"m",
"=",
"post_quat",
".",
"copy",
"(",
")",
"m",
".",
"rotate",
"(",
"psk_bone",
".",
"mat_world",
")",
"m",
"=",
"m",
".",
"to_matrix",
"(",
")",
".",
"to_4x4",
"(",
")",
"m",
".",
"translation",
"=",
"psk_bone",
".",
"mat_world",
".",
"translation",
"edit_bone",
".",
"matrix",
"=",
"m",
"# some dev code...",
"#### FINAL",
"# post_quat = psk_bone.orig_quat.conjugated() * quat_diff",
"# edit_bone.matrix = psk_bone.mat_world * test_quat.to_matrix().to_4x4()",
"# edit_bone[\"post_quat\"] = test_quat",
"#### ",
"# edit_bone[\"post_quat\"] = Quaternion((1,0,0,0))",
"# edit_bone.matrix = psk_bone.mat_world* psk_bone.rot",
"# if edit_bone.parent:",
"# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (psk_bone.orig_quat.conjugated().to_matrix().to_4x4())",
"# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (test_quat.to_matrix().to_4x4())",
"# else:",
"# edit_bone.matrix = psk_bone.orig_quat.to_matrix().to_4x4()",
"# save bindPose information for .psa import",
"# dev",
"edit_bone",
"[",
"\"orig_quat\"",
"]",
"=",
"psk_bone",
".",
"orig_quat",
"edit_bone",
"[",
"\"orig_loc\"",
"]",
"=",
"psk_bone",
".",
"orig_loc",
"edit_bone",
"[",
"\"post_quat\"",
"]",
"=",
"post_quat",
"'''\n bone = edit_bone\n if psk_bone.parent is not None:\n orig_loc = bone.matrix.translation - bone.parent.matrix.translation\n orig_loc.rotate( bone.parent.matrix.to_quaternion().conjugated() )\n\n \n orig_quat = bone.matrix.to_quaternion()\n orig_quat.rotate( bone.parent.matrix.to_quaternion().conjugated() )\n orig_quat.conjugate()\n\n if orig_quat.dot( psk_bone.orig_quat ) < 0.95:\n print(bone.name, psk_bone.orig_quat, orig_quat, orig_quat.dot( psk_bone.orig_quat ))\n print('parent:', bone.parent.matrix.to_quaternion(), bone.parent.matrix.to_quaternion().rotation_difference(bone.matrix.to_quaternion()) )\n\n\n if (psk_bone.orig_loc - orig_loc).length > 0.02:\n print(bone.name, psk_bone.orig_loc, orig_loc, (psk_bone.orig_loc - orig_loc).length)\n '''",
"utils_set_mode",
"(",
"'OBJECT'",
")",
"#==================================================================================================",
"# Weights",
"if",
"bImportmesh",
":",
"vertices_total",
"=",
"len",
"(",
"Vertices",
")",
"for",
"(",
"_",
",",
"PointIndex",
",",
"BoneIndex",
")",
"in",
"Weights",
":",
"if",
"PointIndex",
"<",
"vertices_total",
":",
"# can it be not?",
"psk_bones",
"[",
"BoneIndex",
"]",
".",
"have_weight_data",
"=",
"True",
"# else:",
"# print(psk_bones[BoneIndex].name, 'for other mesh',PointIndex ,vertices_total)",
"#print(\"weight:\", PointIndex, BoneIndex, Weight)",
"# Weights.append(None)",
"# print(Weights.count(None))",
"# Original vertex colorization code",
"'''\n # Weights.sort( key = lambda wgh: wgh[0])\n if bImportmesh:\n VtxCol = []\n bones_count = len(psk_bones)\n for x in range(bones_count):\n #change the overall darkness of each material in a range between 0.1 and 0.9\n tmpVal = ((float(x) + 1.0) / bones_count * 0.7) + 0.1\n tmpVal = int(tmpVal * 256)\n tmpCol = [tmpVal, tmpVal, tmpVal, 0]\n #Change the color of each material slightly\n if x % 3 == 0:\n if tmpCol[0] < 128:\n tmpCol[0] += 60\n else:\n tmpCol[0] -= 60\n if x % 3 == 1:\n if tmpCol[1] < 128:\n tmpCol[1] += 60\n else:\n tmpCol[1] -= 60\n if x % 3 == 2:\n if tmpCol[2] < 128:\n tmpCol[2] += 60\n else:\n tmpCol[2] -= 60\n #Add the material to the mesh\n VtxCol.append(tmpCol)\n \n for x in range(len(Tmsh.faces)):\n for y in range(len(Tmsh.faces[x].v)):\n #find v in Weights[n][0]\n findVal = Tmsh.faces[x].v[y].index\n n = 0\n while findVal != Weights[n][0]:\n n = n + 1\n TmpCol = VtxCol[Weights[n][1]]\n #check if a vertex has more than one influence\n if n != len(Weights) - 1:\n if Weights[n][0] == Weights[n + 1][0]:\n #if there is more than one influence, use the one with the greater influence\n #for simplicity only 2 influences are checked, 2nd and 3rd influences are usually very small\n if Weights[n][2] < Weights[n + 1][2]:\n TmpCol = VtxCol[Weights[n + 1][1]]\n Tmsh.faces[x].col.append(NMesh.Col(TmpCol[0], TmpCol[1], TmpCol[2], 0))\n '''",
"#===================================================================================================",
"# UV. Setup.",
"if",
"bImportmesh",
":",
"# Trick! Create UV maps BEFORE mesh and get (0,0) coordinates for free!",
"# ...otherwise UV coords will be copied from active, or calculated from mesh...",
"if",
"bSpltiUVdata",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"uv_mat_ids",
")",
")",
":",
"get_uv_layers",
"(",
"mesh_data",
")",
".",
"new",
"(",
"name",
"=",
"NAME_UV_PREFIX",
"+",
"str",
"(",
"i",
")",
")",
"else",
":",
"get_uv_layers",
"(",
"mesh_data",
")",
".",
"new",
"(",
"name",
"=",
"NAME_UV_PREFIX",
"+",
"\"_SINGLE\"",
")",
"for",
"counter",
",",
"uv_data",
"in",
"enumerate",
"(",
"Extrauvs",
")",
":",
"if",
"len",
"(",
"mesh_data",
".",
"uv_layers",
")",
"<",
"MAX_UVS",
":",
"get_uv_layers",
"(",
"mesh_data",
")",
".",
"new",
"(",
"name",
"=",
"\"EXTRAUVS\"",
"+",
"str",
"(",
"counter",
")",
")",
"else",
":",
"Extrauvs",
".",
"remove",
"(",
"uv_data",
")",
"print",
"(",
"'Extra UV layer %s is ignored. Re-import without \"Split UV data\".'",
"%",
"counter",
")",
"#================================================================================================== ",
"# Mesh. Build.",
"mesh_data",
".",
"from_pydata",
"(",
"Vertices",
",",
"[",
"]",
",",
"Faces",
")",
"#==================================================================================================",
"# Vertex Normal. Set.",
"if",
"Normals",
"is",
"not",
"None",
":",
"mesh_data",
".",
"polygons",
".",
"foreach_set",
"(",
"\"use_smooth\"",
",",
"[",
"True",
"]",
"*",
"len",
"(",
"mesh_data",
".",
"polygons",
")",
")",
"mesh_data",
".",
"normals_split_custom_set_from_vertices",
"(",
"Normals",
")",
"mesh_data",
".",
"use_auto_smooth",
"=",
"True",
"#===================================================================================================",
"# UV. Set.",
"if",
"bImportmesh",
":",
"for",
"face",
"in",
"mesh_data",
".",
"polygons",
":",
"face",
".",
"material_index",
"=",
"UV_by_face",
"[",
"face",
".",
"index",
"]",
"[",
"1",
"]",
"uv_layers",
"=",
"mesh_data",
".",
"uv_layers",
"if",
"not",
"bSpltiUVdata",
":",
"uvLayer",
"=",
"uv_layers",
"[",
"0",
"]",
"# per face",
"# for faceIdx, (faceUVs, faceMatIdx, _, _, wmidx) in enumerate(UV_by_face):",
"for",
"faceIdx",
",",
"(",
"faceUVs",
",",
"faceMatIdx",
",",
"WedgeMatIds",
")",
"in",
"enumerate",
"(",
"UV_by_face",
")",
":",
"# per vertex",
"for",
"vertN",
",",
"uv",
"in",
"enumerate",
"(",
"faceUVs",
")",
":",
"loopId",
"=",
"faceIdx",
"*",
"3",
"+",
"vertN",
"if",
"bSpltiUVdata",
":",
"uvLayer",
"=",
"uv_layers",
"[",
"WedgeMatIds",
"[",
"vertN",
"]",
"]",
"uvLayer",
".",
"data",
"[",
"loopId",
"]",
".",
"uv",
"=",
"uv",
"#==================================================================================================",
"# VertexColors",
"if",
"VertexColors",
"is",
"not",
"None",
":",
"vtx_color_layer",
"=",
"mesh_data",
".",
"vertex_colors",
".",
"new",
"(",
"name",
"=",
"\"PSKVTXCOL_0\"",
",",
"do_init",
"=",
"False",
")",
"pervertex",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"Vertices",
")",
"for",
"counter",
",",
"(",
"vertexid",
",",
"_",
",",
"_",
",",
"_",
")",
"in",
"enumerate",
"(",
"Wedges",
")",
":",
"# Is it possible ?",
"if",
"(",
"pervertex",
"[",
"vertexid",
"]",
"is",
"not",
"None",
")",
"and",
"(",
"pervertex",
"[",
"vertexid",
"]",
"!=",
"VertexColors",
"[",
"counter",
"]",
")",
":",
"print",
"(",
"'Not equal vertex colors. '",
",",
"vertexid",
",",
"pervertex",
"[",
"vertexid",
"]",
",",
"VertexColors",
"[",
"counter",
"]",
")",
"pervertex",
"[",
"vertexid",
"]",
"=",
"VertexColors",
"[",
"counter",
"]",
"for",
"counter",
",",
"loop",
"in",
"enumerate",
"(",
"mesh_data",
".",
"loops",
")",
":",
"color",
"=",
"pervertex",
"[",
"loop",
".",
"vertex_index",
"]",
"if",
"color",
"is",
"None",
":",
"vtx_color_layer",
".",
"data",
"[",
"counter",
"]",
".",
"color",
"=",
"(",
"1.",
",",
"1.",
",",
"1.",
",",
"1.",
")",
"else",
":",
"if",
"bToSRGB",
":",
"vtx_color_layer",
".",
"data",
"[",
"counter",
"]",
".",
"color",
"=",
"(",
"color_linear_to_srgb",
"(",
"color",
"[",
"0",
"]",
"/",
"255",
")",
",",
"color_linear_to_srgb",
"(",
"color",
"[",
"1",
"]",
"/",
"255",
")",
",",
"color_linear_to_srgb",
"(",
"color",
"[",
"2",
"]",
"/",
"255",
")",
",",
"color",
"[",
"3",
"]",
"/",
"255",
")",
"else",
":",
"vtx_color_layer",
".",
"data",
"[",
"counter",
"]",
".",
"color",
"=",
"(",
"color",
"[",
"0",
"]",
"/",
"255",
",",
"color",
"[",
"1",
"]",
"/",
"255",
",",
"color",
"[",
"2",
"]",
"/",
"255",
",",
"color",
"[",
"3",
"]",
"/",
"255",
")",
"#===================================================================================================",
"# Extra UVs. Set.",
"# for counter, uv_data in enumerate(Extrauvs):",
"# uvLayer = mesh_data.uv_layers[ counter - len(Extrauvs) ]",
"# for uv_index, uv_coords in enumerate(uv_data):",
"# uvLayer.data[uv_index].uv = (uv_coords[0], 1.0 - uv_coords[1])",
"for",
"counter",
",",
"uv_data",
"in",
"enumerate",
"(",
"Extrauvs",
")",
":",
"uvLayer",
"=",
"mesh_data",
".",
"uv_layers",
"[",
"counter",
"-",
"len",
"(",
"Extrauvs",
")",
"]",
"for",
"faceIdx",
",",
"(",
"WedgeIdx3",
",",
"WedgeIdx2",
",",
"WedgeIdx1",
")",
"in",
"enumerate",
"(",
"WedgeIdx_by_faceIdx",
")",
":",
"# equal to gltf",
"uvLayer",
".",
"data",
"[",
"faceIdx",
"*",
"3",
"]",
".",
"uv",
"=",
"(",
"uv_data",
"[",
"WedgeIdx2",
"]",
"[",
"0",
"]",
",",
"1.0",
"-",
"uv_data",
"[",
"WedgeIdx2",
"]",
"[",
"1",
"]",
")",
"uvLayer",
".",
"data",
"[",
"faceIdx",
"*",
"3",
"+",
"1",
"]",
".",
"uv",
"=",
"(",
"uv_data",
"[",
"WedgeIdx1",
"]",
"[",
"0",
"]",
",",
"1.0",
"-",
"uv_data",
"[",
"WedgeIdx1",
"]",
"[",
"1",
"]",
")",
"uvLayer",
".",
"data",
"[",
"faceIdx",
"*",
"3",
"+",
"2",
"]",
".",
"uv",
"=",
"(",
"uv_data",
"[",
"WedgeIdx3",
"]",
"[",
"0",
"]",
",",
"1.0",
"-",
"uv_data",
"[",
"WedgeIdx3",
"]",
"[",
"1",
"]",
")",
"# uvLayer.data[faceIdx*3 ].uv = (uv_data[WedgeIdx3][0], 1.0 - uv_data[WedgeIdx3][1])",
"# uvLayer.data[faceIdx*3+1].uv = (uv_data[WedgeIdx2][0], 1.0 - uv_data[WedgeIdx2][1])",
"# uvLayer.data[faceIdx*3+2].uv = (uv_data[WedgeIdx1][0], 1.0 - uv_data[WedgeIdx1][1])",
"#===================================================================================================",
"# Mesh. Vertex Groups. Bone Weights.",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"if",
"psk_bone",
".",
"have_weight_data",
":",
"psk_bone",
".",
"vertex_group",
"=",
"mesh_obj",
".",
"vertex_groups",
".",
"new",
"(",
"name",
"=",
"psk_bone",
".",
"name",
")",
"# else:",
"# print(psk_bone.name, 'have no influence on this mesh')",
"for",
"weight",
",",
"vertex_id",
",",
"bone_index_w",
"in",
"filter",
"(",
"None",
",",
"Weights",
")",
":",
"psk_bones",
"[",
"bone_index_w",
"]",
".",
"vertex_group",
".",
"add",
"(",
"(",
"vertex_id",
",",
")",
",",
"weight",
",",
"'ADD'",
")",
"#===================================================================================================",
"# Skeleton. Colorize.",
"if",
"bImportbone",
":",
"bone_group_unused",
"=",
"armature_obj",
".",
"pose",
".",
"bone_groups",
".",
"new",
"(",
"name",
"=",
"\"Unused bones\"",
")",
"bone_group_unused",
".",
"color_set",
"=",
"'THEME14'",
"bone_group_nochild",
"=",
"armature_obj",
".",
"pose",
".",
"bone_groups",
".",
"new",
"(",
"name",
"=",
"\"No children\"",
")",
"bone_group_nochild",
".",
"color_set",
"=",
"'THEME03'",
"armature_data",
".",
"show_group_colors",
"=",
"True",
"for",
"psk_bone",
"in",
"psk_bones",
":",
"pose_bone",
"=",
"armature_obj",
".",
"pose",
".",
"bones",
"[",
"psk_bone",
".",
"name",
"]",
"if",
"psk_bone",
".",
"have_weight_data",
":",
"if",
"len",
"(",
"psk_bone",
".",
"children",
")",
"==",
"0",
":",
"pose_bone",
".",
"bone_group",
"=",
"bone_group_nochild",
"else",
":",
"pose_bone",
".",
"bone_group",
"=",
"bone_group_unused",
"#===================================================================================================",
"# Final",
"if",
"bImportmesh",
":",
"util_obj_link",
"(",
"context",
",",
"mesh_obj",
")",
"util_select_all",
"(",
"False",
")",
"if",
"not",
"bImportbone",
":",
"util_obj_select",
"(",
"context",
",",
"mesh_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"mesh_obj",
")",
"else",
":",
"# select_all(False)",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"# parenting mesh to armature object",
"mesh_obj",
".",
"parent",
"=",
"armature_obj",
"mesh_obj",
".",
"parent_type",
"=",
"'OBJECT'",
"# add armature modifier",
"blender_modifier",
"=",
"mesh_obj",
".",
"modifiers",
".",
"new",
"(",
"armature_obj",
".",
"data",
".",
"name",
",",
"type",
"=",
"'ARMATURE'",
")",
"blender_modifier",
".",
"show_expanded",
"=",
"False",
"blender_modifier",
".",
"use_vertex_groups",
"=",
"True",
"blender_modifier",
".",
"use_bone_envelopes",
"=",
"False",
"blender_modifier",
".",
"object",
"=",
"armature_obj",
"# utils_set_mode('OBJECT')",
"# select_all(False)",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")",
"# print(\"Done: %f sec.\" % (time.process_time() - ref_time))",
"utils_set_mode",
"(",
"'OBJECT'",
")",
"return",
"True"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_280.py#L305-L1220 |
|
Befzz/blender3d_import_psk_psa | 47f1418aef7642f300e0fccbe3c96654ab275a52 | addons/io_import_scene_unreal_psa_psk_280.py | python | psaimport | (filepath,
context = None,
oArmature = None,
bFilenameAsPrefix = False,
bActionsToTrack = False,
first_frames = 0,
bDontInvertRoot = True,
bUpdateTimelineRange = False,
bRotationOnly = False,
bScaleDown = True,
fcurve_interpolation = 'LINEAR',
# error_callback = __pass
error_callback = print
) | Import animation data from 'filepath' using 'oArmature'
Args:
first_frames: (0 - import all)
Import only 'first_frames' from each action
bActionsToTrack:
Put all imported actions in one NLAtrack.
oArmature:
Skeleton used to calculate keyframes | Import animation data from 'filepath' using 'oArmature'
Args:
first_frames: (0 - import all)
Import only 'first_frames' from each action
bActionsToTrack:
Put all imported actions in one NLAtrack.
oArmature:
Skeleton used to calculate keyframes | [
"Import",
"animation",
"data",
"from",
"filepath",
"using",
"oArmature",
"Args",
":",
"first_frames",
":",
"(",
"0",
"-",
"import",
"all",
")",
"Import",
"only",
"first_frames",
"from",
"each",
"action",
"bActionsToTrack",
":",
"Put",
"all",
"imported",
"actions",
"in",
"one",
"NLAtrack",
".",
"oArmature",
":",
"Skeleton",
"used",
"to",
"calculate",
"keyframes"
] | def psaimport(filepath,
context = None,
oArmature = None,
bFilenameAsPrefix = False,
bActionsToTrack = False,
first_frames = 0,
bDontInvertRoot = True,
bUpdateTimelineRange = False,
bRotationOnly = False,
bScaleDown = True,
fcurve_interpolation = 'LINEAR',
# error_callback = __pass
error_callback = print
):
"""Import animation data from 'filepath' using 'oArmature'
Args:
first_frames: (0 - import all)
Import only 'first_frames' from each action
bActionsToTrack:
Put all imported actions in one NLAtrack.
oArmature:
Skeleton used to calculate keyframes
"""
print ("-----------------------------------------------")
print ("---------EXECUTING PSA PYTHON IMPORTER---------")
print ("-----------------------------------------------")
file_ext = 'psa'
try:
psafile = open(filepath, 'rb')
except IOError:
error_callback('Error while opening file for reading:\n "'+filepath+'"')
return False
print ("Importing file: ", filepath)
if not context:
context = bpy.context
armature_obj = oArmature
if armature_obj is None:
armature_obj = blen_get_armature_from_selection()
if armature_obj is None:
error_callback("No armature selected.")
return False
chunk_id = None
chunk_type = None
chunk_datasize = None
chunk_datacount = None
chunk_data = None
def read_chunk():
nonlocal chunk_id, chunk_type,\
chunk_datasize, chunk_datacount,\
chunk_data
(chunk_id, chunk_type,
chunk_datasize, chunk_datacount) = unpack('20s3i', psafile.read(32))
chunk_data = psafile.read(chunk_datacount * chunk_datasize)
#==============================================================================================
# General Header
#==============================================================================================
read_chunk()
if not util_is_header_valid(filepath, file_ext, chunk_id, error_callback):
return False
#==============================================================================================
# Bones (FNamedBoneBinary)
#==============================================================================================
read_chunk()
psa_bones = {}
def new_psa_bone(bone, pose_bone):
psa_bone = class_psa_bone()
psa_bones[pose_bone.name] = psa_bone
psa_bone.name = pose_bone.name
psa_bone.pose_bone = pose_bone
if bone.parent != None:
# does needed parent bone was added from psa file
if bone.parent.name in psa_bones:
psa_bone.parent = psa_bones[bone.parent.name]
# no. armature doesnt match
else:
psa_bone.parent = None
# else:
# psa_bone.parent = None
# brute fix for non psk skeletons
if bone.get('orig_quat') is None:
if bone.parent != None:
psa_bone.orig_loc = bone.matrix_local.translation - bone.parent.matrix_local.translation
psa_bone.orig_loc.rotate( bone.parent.matrix_local.to_quaternion().conjugated() )
psa_bone.orig_quat = bone.matrix_local.to_quaternion()
psa_bone.orig_quat.rotate( bone.parent.matrix_local.to_quaternion().conjugated() )
psa_bone.orig_quat.conjugate()
else:
psa_bone.orig_loc = bone.matrix_local.translation.copy()
psa_bone.orig_quat = bone.matrix_local.to_quaternion()
psa_bone.post_quat = psa_bone.orig_quat.conjugated()
else:
psa_bone.orig_quat = Quaternion(bone['orig_quat'])
psa_bone.orig_loc = Vector(bone['orig_loc'])
psa_bone.post_quat = Quaternion(bone['post_quat'])
return psa_bone
#Bones Data
BoneIndex2Name = [None] * chunk_datacount
BoneNotFoundList = []
BonesWithoutAnimation = []
PsaBonesToProcess = [None] * chunk_datacount
BonePsaImportedNames = []
# printlog("Name\tFlgs\tNumChld\tPrntIdx\tQx\tQy\tQz\tQw\tLocX\tLocY\tLocZ\tLength\tXSize\tYSize\tZSize\n")
# for case insensetive comparison
# key = lowered name
# value = orignal name
skeleton_bones_lowered = {}
for blender_bone_name in armature_obj.data.bones.keys():
skeleton_bones_lowered[blender_bone_name.lower()] = blender_bone_name
for counter in range(chunk_datacount):
# tPrntIdx is -1 for parent; and 0 for other; no more useful data
# indata = unpack_from('64s3i11f', chunk_data, chunk_datasize * counter)
(indata) = unpack_from('64s56x', chunk_data, chunk_datasize * counter)
in_name = util_bytes_to_str(indata[0])
# bonename = util_bytes_to_str(indata[0]).upper()
in_name_lowered = in_name.lower()
if in_name_lowered in skeleton_bones_lowered:
orig_name = skeleton_bones_lowered[in_name_lowered]
count_duplicates = BonePsaImportedNames.count( in_name_lowered )
if count_duplicates > 0:
duplicate_name_numbered = in_name_lowered + ('.%03d' % count_duplicates)
# print('Dup:', in_name_lowered, '~',duplicate_name_numbered)
# Skeleton have duplicate name too?
if duplicate_name_numbered in skeleton_bones_lowered:
orig_name = orig_name + ('.%03d' % count_duplicates)
else:
# Skip animation import for that bone
print(" PSK do not have numbered duplicate name(but PSA have!):", duplicate_name_numbered)
BonePsaImportedNames.append(in_name_lowered)
continue
# use a skeleton bone name
BoneIndex2Name[counter] = orig_name
PsaBonesToProcess[counter] = new_psa_bone(armature_obj.data.bones[orig_name],
armature_obj.pose.bones[orig_name])
BonePsaImportedNames.append(in_name_lowered)
else:
# print("Can't find the bone:", orig_name, in_name_lowered)
BoneNotFoundList.append(counter)
if len(psa_bones) == 0:
error_callback('No bone was match!\nSkip import!')
return False
# does anyone care?
for blender_bone_name in armature_obj.data.bones.keys():
if BoneIndex2Name.count(blender_bone_name) == 0:
BonesWithoutAnimation.append(blender_bone_name)
if len(BoneNotFoundList) > 0:
print('PSA have data for more bones: %i.' % len(BoneNotFoundList))
if len(BonesWithoutAnimation) > 0:
print('PSA do not have data for %i bones:\n' % len(BonesWithoutAnimation), ', '.join(BonesWithoutAnimation))
#==============================================================================================
# Animations (AniminfoBinary)
#==============================================================================================
read_chunk()
Raw_Key_Nums = 0
Action_List = [None] * chunk_datacount
for counter in range(chunk_datacount):
(action_name_raw, #0
group_name_raw, #1
Totalbones, #2
RootInclude, #3
KeyCompressionStyle, #4
KeyQuotum, #5
KeyReduction, #6
TrackTime, #7
AnimRate, #8
StartBone, #9
FirstRawFrame, #10
NumRawFrames #11
) = unpack_from('64s64s4i3f3i', chunk_data, chunk_datasize * counter)
action_name = util_bytes_to_str( action_name_raw )
group_name = util_bytes_to_str( group_name_raw )
Raw_Key_Nums += Totalbones * NumRawFrames
Action_List[counter] = ( action_name, group_name, Totalbones, NumRawFrames)
#==============================================================================================
# Raw keys (VQuatAnimKey) 3f vec, 4f quat, 1f time
#==============================================================================================
read_chunk()
if(Raw_Key_Nums != chunk_datacount):
error_callback(
'Raw_Key_Nums Inconsistent.'
'\nData count found: '+chunk_datacount+
'\nRaw_Key_Nums:' + Raw_Key_Nums
)
return False
Raw_Key_List = [None] * chunk_datacount
unpack_data = Struct('3f4f4x').unpack_from
for counter in range(chunk_datacount):
pos = Vector()
quat = Quaternion()
( pos.x, pos.y, pos.z,
quat.x, quat.y, quat.z, quat.w
) = unpack_data( chunk_data, chunk_datasize * counter)
if bScaleDown:
Raw_Key_List[counter] = (pos * 0.01, quat)
else:
Raw_Key_List[counter] = (pos, quat)
psafile.close()
utils_set_mode('OBJECT')
# index of current frame in raw input data
raw_key_index = 0
util_obj_set_active(context, armature_obj)
gen_name_part = util_gen_name_part(filepath)
armature_obj.animation_data_create()
if bActionsToTrack:
nla_track = armature_obj.animation_data.nla_tracks.new()
nla_track.name = gen_name_part
nla_stripes = nla_track.strips
nla_track_last_frame = 0
if len(armature_obj.animation_data.nla_tracks) > 0:
for track in armature_obj.animation_data.nla_tracks:
if len(track.strips) > 0:
if track.strips[-1].frame_end > nla_track_last_frame:
nla_track_last_frame = track.strips[-1].frame_end
is_first_action = True
first_action = None
for counter, (Name, Group, Totalbones, NumRawFrames) in enumerate(Action_List):
ref_time = time.process_time()
if Group != 'None':
Name = "(%s) %s" % (Group,Name)
if bFilenameAsPrefix:
Name = "(%s) %s" % (gen_name_part, Name)
action = bpy.data.actions.new(name = Name)
# force print usefull information to console(due to possible long execution)
print("Action {0:>3d}/{1:<3d} frames: {2:>4d} {3}".format(
counter+1, len(Action_List), NumRawFrames, Name)
)
if first_frames > 0:
maxframes = first_frames
keyframes = min(first_frames, NumRawFrames)
#dev
# keyframes += 1
else:
maxframes = 99999999
keyframes = NumRawFrames
# create all fcurves(for all bones) for an action
# for pose_bone in armature_obj.pose.bones:
for psa_bone in PsaBonesToProcess:
if psa_bone is None:
continue
pose_bone = psa_bone.pose_bone
data_path = pose_bone.path_from_id("rotation_quaternion")
psa_bone.fcurve_quat_w = action.fcurves.new(data_path, index = 0)
psa_bone.fcurve_quat_x = action.fcurves.new(data_path, index = 1)
psa_bone.fcurve_quat_y = action.fcurves.new(data_path, index = 2)
psa_bone.fcurve_quat_z = action.fcurves.new(data_path, index = 3)
if not bRotationOnly:
data_path = pose_bone.path_from_id("location")
psa_bone.fcurve_loc_x = action.fcurves.new(data_path, index = 0)
psa_bone.fcurve_loc_y = action.fcurves.new(data_path, index = 1)
psa_bone.fcurve_loc_z = action.fcurves.new(data_path, index = 2)
# 1. Pre-add keyframes! \0/
# 2. Set data: keyframe_points[].co[0..1]
# 3. If 2 is not done, do 4: (important!!!)
# 4. "Apply" data: fcurve.update()
# # added keyframes points by default is breaking fcurve somehow
# # bcs they are all at the same position?
psa_bone.fcurve_quat_w.keyframe_points.add(keyframes)
psa_bone.fcurve_quat_x.keyframe_points.add(keyframes)
psa_bone.fcurve_quat_y.keyframe_points.add(keyframes)
psa_bone.fcurve_quat_z.keyframe_points.add(keyframes)
if not bRotationOnly:
psa_bone.fcurve_loc_x.keyframe_points.add(keyframes)
psa_bone.fcurve_loc_y.keyframe_points.add(keyframes)
psa_bone.fcurve_loc_z.keyframe_points.add(keyframes)
for i in range(0,min(maxframes, NumRawFrames)):
# raw_key_index+= Totalbones * 5 #55
for j in range(Totalbones):
if j in BoneNotFoundList:
raw_key_index += 1
continue
psa_bone = PsaBonesToProcess[j]
# pose_bone = psa_bone.pose_bone
p_pos = Raw_Key_List[raw_key_index][0]
p_quat = Raw_Key_List[raw_key_index][1]
# @
# if psa_bone.parent:
# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
# else:
# if bDontInvertRoot:
# quat = (p_quat.conjugated() * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
# else:
# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
q = psa_bone.post_quat.copy()
q.rotate( psa_bone.orig_quat )
quat = q
q = psa_bone.post_quat.copy()
if psa_bone.parent == None and bDontInvertRoot:
q.rotate( p_quat.conjugated() )
else:
q.rotate( p_quat )
quat.rotate( q.conjugated() )
# @
# loc = psa_bone.post_quat.conjugated() * p_pos - psa_bone.post_quat.conjugated() * psa_bone.orig_loc
if not bRotationOnly:
loc = (p_pos - psa_bone.orig_loc)
# "edit bone" location is in "parent space"
# but "pose bone" location is in "local space(bone)"
# so we need to transform from parent(edit_bone) to local space (pose_bone)
loc.rotate( psa_bone.post_quat.conjugated() )
# if not bRotationOnly:
# loc = (p_pos - psa_bone.orig_loc)
# if psa_bone.parent is not None:
# q = psa_bone.parent.post_quat.copy()
# q.rotate( psa_bone.parent.orig_quat )
# print(q)
# loc.rotate( psa_bone.parent.post_quat.conjugated() )
# loc.rotate( q.conjugated() )
# loc.rotate( q )
# pass
# quat = p_quat.conjugated()
# quat = p_quat
# quat.rotate( psa_bone.orig_quat.conjugated() )
# quat = Quaternion()
# loc = -p_pos
# loc = (p_pos - psa_bone.orig_loc)
# loc = Vector()
# loc.rotate( psa_bone.post_quat.conjugated() )
# Set it?
# pose_bone.rotation_quaternion = quat
# pose_bone.location = loc
# pose_bone.rotation_quaternion = orig_rot.conjugated()
# pose_bone.location = p_pos - (pose_bone.bone.matrix_local.translation - pose_bone.bone.parent.matrix_local.translation)
##### Works + post_quat (without location works)
# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)
# loc = psa_bone.post_quat.conjugated() * (p_pos - psa_bone.orig_loc)
psa_bone.fcurve_quat_w.keyframe_points[i].co = i, quat.w
psa_bone.fcurve_quat_x.keyframe_points[i].co = i, quat.x
psa_bone.fcurve_quat_y.keyframe_points[i].co = i, quat.y
psa_bone.fcurve_quat_z.keyframe_points[i].co = i, quat.z
psa_bone.fcurve_quat_w.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_quat_x.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_quat_y.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_quat_z.keyframe_points[i].interpolation = fcurve_interpolation
if not bRotationOnly:
psa_bone.fcurve_loc_x.keyframe_points[i].co = i, loc.x
psa_bone.fcurve_loc_y.keyframe_points[i].co = i, loc.y
psa_bone.fcurve_loc_z.keyframe_points[i].co = i, loc.z
psa_bone.fcurve_loc_x.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_loc_y.keyframe_points[i].interpolation = fcurve_interpolation
psa_bone.fcurve_loc_z.keyframe_points[i].interpolation = fcurve_interpolation
# Old path. Slower.
# psa_bone.fcurve_quat_w.keyframe_points.insert(i,quat.w,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_quat_x.keyframe_points.insert(i,quat.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_quat_y.keyframe_points.insert(i,quat.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_quat_z.keyframe_points.insert(i,quat.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_loc_x.keyframe_points.insert(i,loc.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_loc_y.keyframe_points.insert(i,loc.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
# psa_bone.fcurve_loc_z.keyframe_points.insert(i,loc.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation
raw_key_index += 1
# on first frame
# break
raw_key_index += (NumRawFrames-min(maxframes,NumRawFrames)) * Totalbones
# Add action to tail of the nla track
if bActionsToTrack:
if len(nla_track.strips) == 0:
strip = nla_stripes.new(Name, nla_track_last_frame, action)
else:
strip = nla_stripes.new(Name, nla_stripes[-1].frame_end, action)
# Do not pollute track. Makes other tracks 'visible' through 'empty space'.
strip.extrapolation = 'NOTHING'
nla_track_last_frame += NumRawFrames
if is_first_action:
first_action = action
is_first_action = False
print("Done: %f sec." % (time.process_time() - ref_time))
# break on first animation set
# break
scene = util_get_scene(context)
if not bActionsToTrack:
if not scene.is_nla_tweakmode:
armature_obj.animation_data.action = first_action
if bUpdateTimelineRange:
scene.frame_start = 0
if bActionsToTrack:
scene.frame_end = sum(frames for _, _, _, frames in Action_List) - 1
else:
scene.frame_end = max(frames for _, _, _, frames in Action_List) - 1
util_select_all(False)
util_obj_select(context, armature_obj)
util_obj_set_active(context, armature_obj) | [
"def",
"psaimport",
"(",
"filepath",
",",
"context",
"=",
"None",
",",
"oArmature",
"=",
"None",
",",
"bFilenameAsPrefix",
"=",
"False",
",",
"bActionsToTrack",
"=",
"False",
",",
"first_frames",
"=",
"0",
",",
"bDontInvertRoot",
"=",
"True",
",",
"bUpdateTimelineRange",
"=",
"False",
",",
"bRotationOnly",
"=",
"False",
",",
"bScaleDown",
"=",
"True",
",",
"fcurve_interpolation",
"=",
"'LINEAR'",
",",
"# error_callback = __pass",
"error_callback",
"=",
"print",
")",
":",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"print",
"(",
"\"---------EXECUTING PSA PYTHON IMPORTER---------\"",
")",
"print",
"(",
"\"-----------------------------------------------\"",
")",
"file_ext",
"=",
"'psa'",
"try",
":",
"psafile",
"=",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"except",
"IOError",
":",
"error_callback",
"(",
"'Error while opening file for reading:\\n \"'",
"+",
"filepath",
"+",
"'\"'",
")",
"return",
"False",
"print",
"(",
"\"Importing file: \"",
",",
"filepath",
")",
"if",
"not",
"context",
":",
"context",
"=",
"bpy",
".",
"context",
"armature_obj",
"=",
"oArmature",
"if",
"armature_obj",
"is",
"None",
":",
"armature_obj",
"=",
"blen_get_armature_from_selection",
"(",
")",
"if",
"armature_obj",
"is",
"None",
":",
"error_callback",
"(",
"\"No armature selected.\"",
")",
"return",
"False",
"chunk_id",
"=",
"None",
"chunk_type",
"=",
"None",
"chunk_datasize",
"=",
"None",
"chunk_datacount",
"=",
"None",
"chunk_data",
"=",
"None",
"def",
"read_chunk",
"(",
")",
":",
"nonlocal",
"chunk_id",
",",
"chunk_type",
",",
"chunk_datasize",
",",
"chunk_datacount",
",",
"chunk_data",
"(",
"chunk_id",
",",
"chunk_type",
",",
"chunk_datasize",
",",
"chunk_datacount",
")",
"=",
"unpack",
"(",
"'20s3i'",
",",
"psafile",
".",
"read",
"(",
"32",
")",
")",
"chunk_data",
"=",
"psafile",
".",
"read",
"(",
"chunk_datacount",
"*",
"chunk_datasize",
")",
"#============================================================================================== ",
"# General Header",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"if",
"not",
"util_is_header_valid",
"(",
"filepath",
",",
"file_ext",
",",
"chunk_id",
",",
"error_callback",
")",
":",
"return",
"False",
"#============================================================================================== ",
"# Bones (FNamedBoneBinary)",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"psa_bones",
"=",
"{",
"}",
"def",
"new_psa_bone",
"(",
"bone",
",",
"pose_bone",
")",
":",
"psa_bone",
"=",
"class_psa_bone",
"(",
")",
"psa_bones",
"[",
"pose_bone",
".",
"name",
"]",
"=",
"psa_bone",
"psa_bone",
".",
"name",
"=",
"pose_bone",
".",
"name",
"psa_bone",
".",
"pose_bone",
"=",
"pose_bone",
"if",
"bone",
".",
"parent",
"!=",
"None",
":",
"# does needed parent bone was added from psa file",
"if",
"bone",
".",
"parent",
".",
"name",
"in",
"psa_bones",
":",
"psa_bone",
".",
"parent",
"=",
"psa_bones",
"[",
"bone",
".",
"parent",
".",
"name",
"]",
"# no. armature doesnt match",
"else",
":",
"psa_bone",
".",
"parent",
"=",
"None",
"# else:",
"# psa_bone.parent = None",
"# brute fix for non psk skeletons",
"if",
"bone",
".",
"get",
"(",
"'orig_quat'",
")",
"is",
"None",
":",
"if",
"bone",
".",
"parent",
"!=",
"None",
":",
"psa_bone",
".",
"orig_loc",
"=",
"bone",
".",
"matrix_local",
".",
"translation",
"-",
"bone",
".",
"parent",
".",
"matrix_local",
".",
"translation",
"psa_bone",
".",
"orig_loc",
".",
"rotate",
"(",
"bone",
".",
"parent",
".",
"matrix_local",
".",
"to_quaternion",
"(",
")",
".",
"conjugated",
"(",
")",
")",
"psa_bone",
".",
"orig_quat",
"=",
"bone",
".",
"matrix_local",
".",
"to_quaternion",
"(",
")",
"psa_bone",
".",
"orig_quat",
".",
"rotate",
"(",
"bone",
".",
"parent",
".",
"matrix_local",
".",
"to_quaternion",
"(",
")",
".",
"conjugated",
"(",
")",
")",
"psa_bone",
".",
"orig_quat",
".",
"conjugate",
"(",
")",
"else",
":",
"psa_bone",
".",
"orig_loc",
"=",
"bone",
".",
"matrix_local",
".",
"translation",
".",
"copy",
"(",
")",
"psa_bone",
".",
"orig_quat",
"=",
"bone",
".",
"matrix_local",
".",
"to_quaternion",
"(",
")",
"psa_bone",
".",
"post_quat",
"=",
"psa_bone",
".",
"orig_quat",
".",
"conjugated",
"(",
")",
"else",
":",
"psa_bone",
".",
"orig_quat",
"=",
"Quaternion",
"(",
"bone",
"[",
"'orig_quat'",
"]",
")",
"psa_bone",
".",
"orig_loc",
"=",
"Vector",
"(",
"bone",
"[",
"'orig_loc'",
"]",
")",
"psa_bone",
".",
"post_quat",
"=",
"Quaternion",
"(",
"bone",
"[",
"'post_quat'",
"]",
")",
"return",
"psa_bone",
"#Bones Data",
"BoneIndex2Name",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"BoneNotFoundList",
"=",
"[",
"]",
"BonesWithoutAnimation",
"=",
"[",
"]",
"PsaBonesToProcess",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"BonePsaImportedNames",
"=",
"[",
"]",
"# printlog(\"Name\\tFlgs\\tNumChld\\tPrntIdx\\tQx\\tQy\\tQz\\tQw\\tLocX\\tLocY\\tLocZ\\tLength\\tXSize\\tYSize\\tZSize\\n\")",
"# for case insensetive comparison",
"# key = lowered name",
"# value = orignal name",
"skeleton_bones_lowered",
"=",
"{",
"}",
"for",
"blender_bone_name",
"in",
"armature_obj",
".",
"data",
".",
"bones",
".",
"keys",
"(",
")",
":",
"skeleton_bones_lowered",
"[",
"blender_bone_name",
".",
"lower",
"(",
")",
"]",
"=",
"blender_bone_name",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"# tPrntIdx is -1 for parent; and 0 for other; no more useful data",
"# indata = unpack_from('64s3i11f', chunk_data, chunk_datasize * counter)",
"(",
"indata",
")",
"=",
"unpack_from",
"(",
"'64s56x'",
",",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"in_name",
"=",
"util_bytes_to_str",
"(",
"indata",
"[",
"0",
"]",
")",
"# bonename = util_bytes_to_str(indata[0]).upper()",
"in_name_lowered",
"=",
"in_name",
".",
"lower",
"(",
")",
"if",
"in_name_lowered",
"in",
"skeleton_bones_lowered",
":",
"orig_name",
"=",
"skeleton_bones_lowered",
"[",
"in_name_lowered",
"]",
"count_duplicates",
"=",
"BonePsaImportedNames",
".",
"count",
"(",
"in_name_lowered",
")",
"if",
"count_duplicates",
">",
"0",
":",
"duplicate_name_numbered",
"=",
"in_name_lowered",
"+",
"(",
"'.%03d'",
"%",
"count_duplicates",
")",
"# print('Dup:', in_name_lowered, '~',duplicate_name_numbered)",
"# Skeleton have duplicate name too?",
"if",
"duplicate_name_numbered",
"in",
"skeleton_bones_lowered",
":",
"orig_name",
"=",
"orig_name",
"+",
"(",
"'.%03d'",
"%",
"count_duplicates",
")",
"else",
":",
"# Skip animation import for that bone",
"print",
"(",
"\" PSK do not have numbered duplicate name(but PSA have!):\"",
",",
"duplicate_name_numbered",
")",
"BonePsaImportedNames",
".",
"append",
"(",
"in_name_lowered",
")",
"continue",
"# use a skeleton bone name ",
"BoneIndex2Name",
"[",
"counter",
"]",
"=",
"orig_name",
"PsaBonesToProcess",
"[",
"counter",
"]",
"=",
"new_psa_bone",
"(",
"armature_obj",
".",
"data",
".",
"bones",
"[",
"orig_name",
"]",
",",
"armature_obj",
".",
"pose",
".",
"bones",
"[",
"orig_name",
"]",
")",
"BonePsaImportedNames",
".",
"append",
"(",
"in_name_lowered",
")",
"else",
":",
"# print(\"Can't find the bone:\", orig_name, in_name_lowered)",
"BoneNotFoundList",
".",
"append",
"(",
"counter",
")",
"if",
"len",
"(",
"psa_bones",
")",
"==",
"0",
":",
"error_callback",
"(",
"'No bone was match!\\nSkip import!'",
")",
"return",
"False",
"# does anyone care?",
"for",
"blender_bone_name",
"in",
"armature_obj",
".",
"data",
".",
"bones",
".",
"keys",
"(",
")",
":",
"if",
"BoneIndex2Name",
".",
"count",
"(",
"blender_bone_name",
")",
"==",
"0",
":",
"BonesWithoutAnimation",
".",
"append",
"(",
"blender_bone_name",
")",
"if",
"len",
"(",
"BoneNotFoundList",
")",
">",
"0",
":",
"print",
"(",
"'PSA have data for more bones: %i.'",
"%",
"len",
"(",
"BoneNotFoundList",
")",
")",
"if",
"len",
"(",
"BonesWithoutAnimation",
")",
">",
"0",
":",
"print",
"(",
"'PSA do not have data for %i bones:\\n'",
"%",
"len",
"(",
"BonesWithoutAnimation",
")",
",",
"', '",
".",
"join",
"(",
"BonesWithoutAnimation",
")",
")",
"#============================================================================================== ",
"# Animations (AniminfoBinary)",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"Raw_Key_Nums",
"=",
"0",
"Action_List",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"(",
"action_name_raw",
",",
"#0",
"group_name_raw",
",",
"#1",
"Totalbones",
",",
"#2",
"RootInclude",
",",
"#3",
"KeyCompressionStyle",
",",
"#4",
"KeyQuotum",
",",
"#5",
"KeyReduction",
",",
"#6",
"TrackTime",
",",
"#7",
"AnimRate",
",",
"#8",
"StartBone",
",",
"#9",
"FirstRawFrame",
",",
"#10",
"NumRawFrames",
"#11",
")",
"=",
"unpack_from",
"(",
"'64s64s4i3f3i'",
",",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"action_name",
"=",
"util_bytes_to_str",
"(",
"action_name_raw",
")",
"group_name",
"=",
"util_bytes_to_str",
"(",
"group_name_raw",
")",
"Raw_Key_Nums",
"+=",
"Totalbones",
"*",
"NumRawFrames",
"Action_List",
"[",
"counter",
"]",
"=",
"(",
"action_name",
",",
"group_name",
",",
"Totalbones",
",",
"NumRawFrames",
")",
"#============================================================================================== ",
"# Raw keys (VQuatAnimKey) 3f vec, 4f quat, 1f time",
"#============================================================================================== ",
"read_chunk",
"(",
")",
"if",
"(",
"Raw_Key_Nums",
"!=",
"chunk_datacount",
")",
":",
"error_callback",
"(",
"'Raw_Key_Nums Inconsistent.'",
"'\\nData count found: '",
"+",
"chunk_datacount",
"+",
"'\\nRaw_Key_Nums:'",
"+",
"Raw_Key_Nums",
")",
"return",
"False",
"Raw_Key_List",
"=",
"[",
"None",
"]",
"*",
"chunk_datacount",
"unpack_data",
"=",
"Struct",
"(",
"'3f4f4x'",
")",
".",
"unpack_from",
"for",
"counter",
"in",
"range",
"(",
"chunk_datacount",
")",
":",
"pos",
"=",
"Vector",
"(",
")",
"quat",
"=",
"Quaternion",
"(",
")",
"(",
"pos",
".",
"x",
",",
"pos",
".",
"y",
",",
"pos",
".",
"z",
",",
"quat",
".",
"x",
",",
"quat",
".",
"y",
",",
"quat",
".",
"z",
",",
"quat",
".",
"w",
")",
"=",
"unpack_data",
"(",
"chunk_data",
",",
"chunk_datasize",
"*",
"counter",
")",
"if",
"bScaleDown",
":",
"Raw_Key_List",
"[",
"counter",
"]",
"=",
"(",
"pos",
"*",
"0.01",
",",
"quat",
")",
"else",
":",
"Raw_Key_List",
"[",
"counter",
"]",
"=",
"(",
"pos",
",",
"quat",
")",
"psafile",
".",
"close",
"(",
")",
"utils_set_mode",
"(",
"'OBJECT'",
")",
"# index of current frame in raw input data",
"raw_key_index",
"=",
"0",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")",
"gen_name_part",
"=",
"util_gen_name_part",
"(",
"filepath",
")",
"armature_obj",
".",
"animation_data_create",
"(",
")",
"if",
"bActionsToTrack",
":",
"nla_track",
"=",
"armature_obj",
".",
"animation_data",
".",
"nla_tracks",
".",
"new",
"(",
")",
"nla_track",
".",
"name",
"=",
"gen_name_part",
"nla_stripes",
"=",
"nla_track",
".",
"strips",
"nla_track_last_frame",
"=",
"0",
"if",
"len",
"(",
"armature_obj",
".",
"animation_data",
".",
"nla_tracks",
")",
">",
"0",
":",
"for",
"track",
"in",
"armature_obj",
".",
"animation_data",
".",
"nla_tracks",
":",
"if",
"len",
"(",
"track",
".",
"strips",
")",
">",
"0",
":",
"if",
"track",
".",
"strips",
"[",
"-",
"1",
"]",
".",
"frame_end",
">",
"nla_track_last_frame",
":",
"nla_track_last_frame",
"=",
"track",
".",
"strips",
"[",
"-",
"1",
"]",
".",
"frame_end",
"is_first_action",
"=",
"True",
"first_action",
"=",
"None",
"for",
"counter",
",",
"(",
"Name",
",",
"Group",
",",
"Totalbones",
",",
"NumRawFrames",
")",
"in",
"enumerate",
"(",
"Action_List",
")",
":",
"ref_time",
"=",
"time",
".",
"process_time",
"(",
")",
"if",
"Group",
"!=",
"'None'",
":",
"Name",
"=",
"\"(%s) %s\"",
"%",
"(",
"Group",
",",
"Name",
")",
"if",
"bFilenameAsPrefix",
":",
"Name",
"=",
"\"(%s) %s\"",
"%",
"(",
"gen_name_part",
",",
"Name",
")",
"action",
"=",
"bpy",
".",
"data",
".",
"actions",
".",
"new",
"(",
"name",
"=",
"Name",
")",
"# force print usefull information to console(due to possible long execution)",
"print",
"(",
"\"Action {0:>3d}/{1:<3d} frames: {2:>4d} {3}\"",
".",
"format",
"(",
"counter",
"+",
"1",
",",
"len",
"(",
"Action_List",
")",
",",
"NumRawFrames",
",",
"Name",
")",
")",
"if",
"first_frames",
">",
"0",
":",
"maxframes",
"=",
"first_frames",
"keyframes",
"=",
"min",
"(",
"first_frames",
",",
"NumRawFrames",
")",
"#dev",
"# keyframes += 1",
"else",
":",
"maxframes",
"=",
"99999999",
"keyframes",
"=",
"NumRawFrames",
"# create all fcurves(for all bones) for an action",
"# for pose_bone in armature_obj.pose.bones:",
"for",
"psa_bone",
"in",
"PsaBonesToProcess",
":",
"if",
"psa_bone",
"is",
"None",
":",
"continue",
"pose_bone",
"=",
"psa_bone",
".",
"pose_bone",
"data_path",
"=",
"pose_bone",
".",
"path_from_id",
"(",
"\"rotation_quaternion\"",
")",
"psa_bone",
".",
"fcurve_quat_w",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"0",
")",
"psa_bone",
".",
"fcurve_quat_x",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"1",
")",
"psa_bone",
".",
"fcurve_quat_y",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"2",
")",
"psa_bone",
".",
"fcurve_quat_z",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"3",
")",
"if",
"not",
"bRotationOnly",
":",
"data_path",
"=",
"pose_bone",
".",
"path_from_id",
"(",
"\"location\"",
")",
"psa_bone",
".",
"fcurve_loc_x",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"0",
")",
"psa_bone",
".",
"fcurve_loc_y",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"1",
")",
"psa_bone",
".",
"fcurve_loc_z",
"=",
"action",
".",
"fcurves",
".",
"new",
"(",
"data_path",
",",
"index",
"=",
"2",
")",
"# 1. Pre-add keyframes! \\0/",
"# 2. Set data: keyframe_points[].co[0..1]",
"# 3. If 2 is not done, do 4: (important!!!)",
"# 4. \"Apply\" data: fcurve.update()",
"# # added keyframes points by default is breaking fcurve somehow",
"# # bcs they are all at the same position?",
"psa_bone",
".",
"fcurve_quat_w",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_quat_x",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_quat_y",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_quat_z",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"if",
"not",
"bRotationOnly",
":",
"psa_bone",
".",
"fcurve_loc_x",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_loc_y",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"psa_bone",
".",
"fcurve_loc_z",
".",
"keyframe_points",
".",
"add",
"(",
"keyframes",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"maxframes",
",",
"NumRawFrames",
")",
")",
":",
"# raw_key_index+= Totalbones * 5 #55",
"for",
"j",
"in",
"range",
"(",
"Totalbones",
")",
":",
"if",
"j",
"in",
"BoneNotFoundList",
":",
"raw_key_index",
"+=",
"1",
"continue",
"psa_bone",
"=",
"PsaBonesToProcess",
"[",
"j",
"]",
"# pose_bone = psa_bone.pose_bone",
"p_pos",
"=",
"Raw_Key_List",
"[",
"raw_key_index",
"]",
"[",
"0",
"]",
"p_quat",
"=",
"Raw_Key_List",
"[",
"raw_key_index",
"]",
"[",
"1",
"]",
"# @",
"# if psa_bone.parent:",
"# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)",
"# else:",
"# if bDontInvertRoot:",
"# quat = (p_quat.conjugated() * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)",
"# else:",
"# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)",
"q",
"=",
"psa_bone",
".",
"post_quat",
".",
"copy",
"(",
")",
"q",
".",
"rotate",
"(",
"psa_bone",
".",
"orig_quat",
")",
"quat",
"=",
"q",
"q",
"=",
"psa_bone",
".",
"post_quat",
".",
"copy",
"(",
")",
"if",
"psa_bone",
".",
"parent",
"==",
"None",
"and",
"bDontInvertRoot",
":",
"q",
".",
"rotate",
"(",
"p_quat",
".",
"conjugated",
"(",
")",
")",
"else",
":",
"q",
".",
"rotate",
"(",
"p_quat",
")",
"quat",
".",
"rotate",
"(",
"q",
".",
"conjugated",
"(",
")",
")",
"# @",
"# loc = psa_bone.post_quat.conjugated() * p_pos - psa_bone.post_quat.conjugated() * psa_bone.orig_loc",
"if",
"not",
"bRotationOnly",
":",
"loc",
"=",
"(",
"p_pos",
"-",
"psa_bone",
".",
"orig_loc",
")",
"# \"edit bone\" location is in \"parent space\"",
"# but \"pose bone\" location is in \"local space(bone)\"",
"# so we need to transform from parent(edit_bone) to local space (pose_bone)",
"loc",
".",
"rotate",
"(",
"psa_bone",
".",
"post_quat",
".",
"conjugated",
"(",
")",
")",
"# if not bRotationOnly:",
"# loc = (p_pos - psa_bone.orig_loc)",
"# if psa_bone.parent is not None:",
"# q = psa_bone.parent.post_quat.copy()",
"# q.rotate( psa_bone.parent.orig_quat )",
"# print(q)",
"# loc.rotate( psa_bone.parent.post_quat.conjugated() )",
"# loc.rotate( q.conjugated() )",
"# loc.rotate( q )",
"# pass",
"# quat = p_quat.conjugated()",
"# quat = p_quat",
"# quat.rotate( psa_bone.orig_quat.conjugated() )",
"# quat = Quaternion()",
"# loc = -p_pos",
"# loc = (p_pos - psa_bone.orig_loc)",
"# loc = Vector()",
"# loc.rotate( psa_bone.post_quat.conjugated() )",
"# Set it?",
"# pose_bone.rotation_quaternion = quat",
"# pose_bone.location = loc",
"# pose_bone.rotation_quaternion = orig_rot.conjugated()",
"# pose_bone.location = p_pos - (pose_bone.bone.matrix_local.translation - pose_bone.bone.parent.matrix_local.translation)",
"##### Works + post_quat (without location works)",
"# quat = (p_quat * psa_bone.post_quat).conjugated() * (psa_bone.orig_quat * psa_bone.post_quat)",
"# loc = psa_bone.post_quat.conjugated() * (p_pos - psa_bone.orig_loc)",
"psa_bone",
".",
"fcurve_quat_w",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"w",
"psa_bone",
".",
"fcurve_quat_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"x",
"psa_bone",
".",
"fcurve_quat_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"y",
"psa_bone",
".",
"fcurve_quat_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"quat",
".",
"z",
"psa_bone",
".",
"fcurve_quat_w",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_quat_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_quat_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_quat_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"if",
"not",
"bRotationOnly",
":",
"psa_bone",
".",
"fcurve_loc_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"loc",
".",
"x",
"psa_bone",
".",
"fcurve_loc_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"loc",
".",
"y",
"psa_bone",
".",
"fcurve_loc_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"co",
"=",
"i",
",",
"loc",
".",
"z",
"psa_bone",
".",
"fcurve_loc_x",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_loc_y",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"psa_bone",
".",
"fcurve_loc_z",
".",
"keyframe_points",
"[",
"i",
"]",
".",
"interpolation",
"=",
"fcurve_interpolation",
"# Old path. Slower.",
"# psa_bone.fcurve_quat_w.keyframe_points.insert(i,quat.w,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_quat_x.keyframe_points.insert(i,quat.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_quat_y.keyframe_points.insert(i,quat.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_quat_z.keyframe_points.insert(i,quat.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_loc_x.keyframe_points.insert(i,loc.x,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_loc_y.keyframe_points.insert(i,loc.y,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"# psa_bone.fcurve_loc_z.keyframe_points.insert(i,loc.z,{'NEEDED','FAST'}).interpolation = fcurve_interpolation",
"raw_key_index",
"+=",
"1",
"# on first frame",
"# break",
"raw_key_index",
"+=",
"(",
"NumRawFrames",
"-",
"min",
"(",
"maxframes",
",",
"NumRawFrames",
")",
")",
"*",
"Totalbones",
"# Add action to tail of the nla track",
"if",
"bActionsToTrack",
":",
"if",
"len",
"(",
"nla_track",
".",
"strips",
")",
"==",
"0",
":",
"strip",
"=",
"nla_stripes",
".",
"new",
"(",
"Name",
",",
"nla_track_last_frame",
",",
"action",
")",
"else",
":",
"strip",
"=",
"nla_stripes",
".",
"new",
"(",
"Name",
",",
"nla_stripes",
"[",
"-",
"1",
"]",
".",
"frame_end",
",",
"action",
")",
"# Do not pollute track. Makes other tracks 'visible' through 'empty space'.",
"strip",
".",
"extrapolation",
"=",
"'NOTHING'",
"nla_track_last_frame",
"+=",
"NumRawFrames",
"if",
"is_first_action",
":",
"first_action",
"=",
"action",
"is_first_action",
"=",
"False",
"print",
"(",
"\"Done: %f sec.\"",
"%",
"(",
"time",
".",
"process_time",
"(",
")",
"-",
"ref_time",
")",
")",
"# break on first animation set",
"# break",
"scene",
"=",
"util_get_scene",
"(",
"context",
")",
"if",
"not",
"bActionsToTrack",
":",
"if",
"not",
"scene",
".",
"is_nla_tweakmode",
":",
"armature_obj",
".",
"animation_data",
".",
"action",
"=",
"first_action",
"if",
"bUpdateTimelineRange",
":",
"scene",
".",
"frame_start",
"=",
"0",
"if",
"bActionsToTrack",
":",
"scene",
".",
"frame_end",
"=",
"sum",
"(",
"frames",
"for",
"_",
",",
"_",
",",
"_",
",",
"frames",
"in",
"Action_List",
")",
"-",
"1",
"else",
":",
"scene",
".",
"frame_end",
"=",
"max",
"(",
"frames",
"for",
"_",
",",
"_",
",",
"_",
",",
"frames",
"in",
"Action_List",
")",
"-",
"1",
"util_select_all",
"(",
"False",
")",
"util_obj_select",
"(",
"context",
",",
"armature_obj",
")",
"util_obj_set_active",
"(",
"context",
",",
"armature_obj",
")"
] | https://github.com/Befzz/blender3d_import_psk_psa/blob/47f1418aef7642f300e0fccbe3c96654ab275a52/addons/io_import_scene_unreal_psa_psk_280.py#L1262-L1759 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.__init__ | (self, base_url=None, symbol=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_', shouldWSAuth=True) | Init connector. | Init connector. | [
"Init",
"connector",
"."
] | def __init__(self, base_url=None, symbol=None, login=None, password=None, otpToken=None,
apiKey=None, apiSecret=None, orderIDPrefix='mm_bitmex_', shouldWSAuth=True):
"""Init connector."""
self.logger = logging.getLogger('root')
self.base_url = base_url
self.symbol = symbol
self.token = None
# User/pass auth is no longer supported
if (login or password or otpToken):
raise Exception("User/password authentication is no longer supported via the API. Please use " +
"an API key. You can generate one at https://www.bitmex.com/app/apiKeys")
self.apiKey = apiKey
self.apiSecret = apiSecret
if len(orderIDPrefix) > 13:
raise ValueError("settings.ORDERID_PREFIX must be at most 13 characters long!")
self.orderIDPrefix = orderIDPrefix
# Prepare HTTPS session
self.session = requests.Session()
# These headers are always sent
self.session.headers.update({'user-agent': 'liquidbot-' + constants.VERSION})
self.session.headers.update({'content-type': 'application/json'})
self.session.headers.update({'accept': 'application/json'})
# Create websocket for streaming data
self.ws = BitMEXWebsocket()
self.ws.connect(base_url, symbol, shouldAuth=shouldWSAuth) | [
"def",
"__init__",
"(",
"self",
",",
"base_url",
"=",
"None",
",",
"symbol",
"=",
"None",
",",
"login",
"=",
"None",
",",
"password",
"=",
"None",
",",
"otpToken",
"=",
"None",
",",
"apiKey",
"=",
"None",
",",
"apiSecret",
"=",
"None",
",",
"orderIDPrefix",
"=",
"'mm_bitmex_'",
",",
"shouldWSAuth",
"=",
"True",
")",
":",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'root'",
")",
"self",
".",
"base_url",
"=",
"base_url",
"self",
".",
"symbol",
"=",
"symbol",
"self",
".",
"token",
"=",
"None",
"# User/pass auth is no longer supported",
"if",
"(",
"login",
"or",
"password",
"or",
"otpToken",
")",
":",
"raise",
"Exception",
"(",
"\"User/password authentication is no longer supported via the API. Please use \"",
"+",
"\"an API key. You can generate one at https://www.bitmex.com/app/apiKeys\"",
")",
"self",
".",
"apiKey",
"=",
"apiKey",
"self",
".",
"apiSecret",
"=",
"apiSecret",
"if",
"len",
"(",
"orderIDPrefix",
")",
">",
"13",
":",
"raise",
"ValueError",
"(",
"\"settings.ORDERID_PREFIX must be at most 13 characters long!\"",
")",
"self",
".",
"orderIDPrefix",
"=",
"orderIDPrefix",
"# Prepare HTTPS session",
"self",
".",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"# These headers are always sent",
"self",
".",
"session",
".",
"headers",
".",
"update",
"(",
"{",
"'user-agent'",
":",
"'liquidbot-'",
"+",
"constants",
".",
"VERSION",
"}",
")",
"self",
".",
"session",
".",
"headers",
".",
"update",
"(",
"{",
"'content-type'",
":",
"'application/json'",
"}",
")",
"self",
".",
"session",
".",
"headers",
".",
"update",
"(",
"{",
"'accept'",
":",
"'application/json'",
"}",
")",
"# Create websocket for streaming data",
"self",
".",
"ws",
"=",
"BitMEXWebsocket",
"(",
")",
"self",
".",
"ws",
".",
"connect",
"(",
"base_url",
",",
"symbol",
",",
"shouldAuth",
"=",
"shouldWSAuth",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L19-L45 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.ticker_data | (self, symbol) | return self.ws.get_ticker(symbol) | Get ticker data. | Get ticker data. | [
"Get",
"ticker",
"data",
"."
] | def ticker_data(self, symbol):
"""Get ticker data."""
return self.ws.get_ticker(symbol) | [
"def",
"ticker_data",
"(",
"self",
",",
"symbol",
")",
":",
"return",
"self",
".",
"ws",
".",
"get_ticker",
"(",
"symbol",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L50-L52 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.instrument | (self, symbol) | return self.ws.get_instrument(symbol) | Get an instrument's details. | Get an instrument's details. | [
"Get",
"an",
"instrument",
"s",
"details",
"."
] | def instrument(self, symbol):
"""Get an instrument's details."""
return self.ws.get_instrument(symbol) | [
"def",
"instrument",
"(",
"self",
",",
"symbol",
")",
":",
"return",
"self",
".",
"ws",
".",
"get_instrument",
"(",
"symbol",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L54-L56 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.market_depth | (self, symbol) | return self.ws.market_depth(symbol) | Get market depth / orderbook. | Get market depth / orderbook. | [
"Get",
"market",
"depth",
"/",
"orderbook",
"."
] | def market_depth(self, symbol):
"""Get market depth / orderbook."""
return self.ws.market_depth(symbol) | [
"def",
"market_depth",
"(",
"self",
",",
"symbol",
")",
":",
"return",
"self",
".",
"ws",
".",
"market_depth",
"(",
"symbol",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L58-L60 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.recent_trades | (self, symbol) | return self.ws.recent_trades(symbol) | Get recent trades.
Returns
-------
A list of dicts:
{u'amount': 60,
u'date': 1306775375,
u'price': 8.7401099999999996,
u'tid': u'93842'}, | Get recent trades. | [
"Get",
"recent",
"trades",
"."
] | def recent_trades(self, symbol):
"""Get recent trades.
Returns
-------
A list of dicts:
{u'amount': 60,
u'date': 1306775375,
u'price': 8.7401099999999996,
u'tid': u'93842'},
"""
return self.ws.recent_trades(symbol) | [
"def",
"recent_trades",
"(",
"self",
",",
"symbol",
")",
":",
"return",
"self",
".",
"ws",
".",
"recent_trades",
"(",
"symbol",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L62-L74 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.authentication_required | (function) | return wrapped | Annotation for methods that require auth. | Annotation for methods that require auth. | [
"Annotation",
"for",
"methods",
"that",
"require",
"auth",
"."
] | def authentication_required(function):
"""Annotation for methods that require auth."""
def wrapped(self, *args, **kwargs):
if not (self.apiKey):
msg = "You must be authenticated to use this method"
raise errors.AuthenticationError(msg)
else:
return function(self, *args, **kwargs)
return wrapped | [
"def",
"authentication_required",
"(",
"function",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"self",
".",
"apiKey",
")",
":",
"msg",
"=",
"\"You must be authenticated to use this method\"",
"raise",
"errors",
".",
"AuthenticationError",
"(",
"msg",
")",
"else",
":",
"return",
"function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L79-L87 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.funds | (self) | return self.ws.funds() | Get your current balance. | Get your current balance. | [
"Get",
"your",
"current",
"balance",
"."
] | def funds(self):
"""Get your current balance."""
return self.ws.funds() | [
"def",
"funds",
"(",
"self",
")",
":",
"return",
"self",
".",
"ws",
".",
"funds",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L90-L92 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.position | (self, symbol) | return self.ws.position(symbol) | Get your open position. | Get your open position. | [
"Get",
"your",
"open",
"position",
"."
] | def position(self, symbol):
"""Get your open position."""
return self.ws.position(symbol) | [
"def",
"position",
"(",
"self",
",",
"symbol",
")",
":",
"return",
"self",
".",
"ws",
".",
"position",
"(",
"symbol",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L95-L97 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.buy | (self, quantity, price) | return self.place_order(quantity, price) | Place a buy order.
Returns order object. ID: orderID | Place a buy order. | [
"Place",
"a",
"buy",
"order",
"."
] | def buy(self, quantity, price):
"""Place a buy order.
Returns order object. ID: orderID
"""
return self.place_order(quantity, price) | [
"def",
"buy",
"(",
"self",
",",
"quantity",
",",
"price",
")",
":",
"return",
"self",
".",
"place_order",
"(",
"quantity",
",",
"price",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L100-L105 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.sell | (self, quantity, price) | return self.place_order(-quantity, price) | Place a sell order.
Returns order object. ID: orderID | Place a sell order. | [
"Place",
"a",
"sell",
"order",
"."
] | def sell(self, quantity, price):
"""Place a sell order.
Returns order object. ID: orderID
"""
return self.place_order(-quantity, price) | [
"def",
"sell",
"(",
"self",
",",
"quantity",
",",
"price",
")",
":",
"return",
"self",
".",
"place_order",
"(",
"-",
"quantity",
",",
"price",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L108-L113 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.place_order | (self, quantity, price) | return self._curl_bitmex(api=endpoint, postdict=postdict, verb="POST") | Place an order. | Place an order. | [
"Place",
"an",
"order",
"."
] | def place_order(self, quantity, price):
"""Place an order."""
if price < 0:
raise Exception("Price must be positive.")
endpoint = "order"
# Generate a unique clOrdID with our prefix so we can identify it.
clOrdID = self.orderIDPrefix + base64.b64encode(uuid.uuid4().bytes).decode('utf-8').rstrip('=\n')
postdict = {
'symbol': self.symbol,
'orderQty': quantity,
'price': price,
'clOrdID': clOrdID,
'execInst': 'ParticipateDoNotInitiate'
}
return self._curl_bitmex(api=endpoint, postdict=postdict, verb="POST") | [
"def",
"place_order",
"(",
"self",
",",
"quantity",
",",
"price",
")",
":",
"if",
"price",
"<",
"0",
":",
"raise",
"Exception",
"(",
"\"Price must be positive.\"",
")",
"endpoint",
"=",
"\"order\"",
"# Generate a unique clOrdID with our prefix so we can identify it.",
"clOrdID",
"=",
"self",
".",
"orderIDPrefix",
"+",
"base64",
".",
"b64encode",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"rstrip",
"(",
"'=\\n'",
")",
"postdict",
"=",
"{",
"'symbol'",
":",
"self",
".",
"symbol",
",",
"'orderQty'",
":",
"quantity",
",",
"'price'",
":",
"price",
",",
"'clOrdID'",
":",
"clOrdID",
",",
"'execInst'",
":",
"'ParticipateDoNotInitiate'",
"}",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
"=",
"endpoint",
",",
"postdict",
"=",
"postdict",
",",
"verb",
"=",
"\"POST\"",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L116-L131 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.amend_bulk_orders | (self, orders) | return self._curl_bitmex(api='order/bulk', postdict={'orders': orders}, verb='PUT', rethrow_errors=True) | Amend multiple orders. | Amend multiple orders. | [
"Amend",
"multiple",
"orders",
"."
] | def amend_bulk_orders(self, orders):
"""Amend multiple orders."""
return self._curl_bitmex(api='order/bulk', postdict={'orders': orders}, verb='PUT', rethrow_errors=True) | [
"def",
"amend_bulk_orders",
"(",
"self",
",",
"orders",
")",
":",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
"=",
"'order/bulk'",
",",
"postdict",
"=",
"{",
"'orders'",
":",
"orders",
"}",
",",
"verb",
"=",
"'PUT'",
",",
"rethrow_errors",
"=",
"True",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L134-L136 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.create_bulk_orders | (self, orders) | return self._curl_bitmex(api='order/bulk', postdict={'orders': orders}, verb='POST') | Create multiple orders. | Create multiple orders. | [
"Create",
"multiple",
"orders",
"."
] | def create_bulk_orders(self, orders):
"""Create multiple orders."""
for order in orders:
order['clOrdID'] = self.orderIDPrefix + base64.b64encode(uuid.uuid4().bytes).decode('utf-8').rstrip('=\n')
order['symbol'] = self.symbol
order['execInst'] = 'ParticipateDoNotInitiate'
return self._curl_bitmex(api='order/bulk', postdict={'orders': orders}, verb='POST') | [
"def",
"create_bulk_orders",
"(",
"self",
",",
"orders",
")",
":",
"for",
"order",
"in",
"orders",
":",
"order",
"[",
"'clOrdID'",
"]",
"=",
"self",
".",
"orderIDPrefix",
"+",
"base64",
".",
"b64encode",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"rstrip",
"(",
"'=\\n'",
")",
"order",
"[",
"'symbol'",
"]",
"=",
"self",
".",
"symbol",
"order",
"[",
"'execInst'",
"]",
"=",
"'ParticipateDoNotInitiate'",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
"=",
"'order/bulk'",
",",
"postdict",
"=",
"{",
"'orders'",
":",
"orders",
"}",
",",
"verb",
"=",
"'POST'",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L139-L145 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.open_orders | (self) | return self.ws.open_orders(self.orderIDPrefix) | Get open orders. | Get open orders. | [
"Get",
"open",
"orders",
"."
] | def open_orders(self):
"""Get open orders."""
return self.ws.open_orders(self.orderIDPrefix) | [
"def",
"open_orders",
"(",
"self",
")",
":",
"return",
"self",
".",
"ws",
".",
"open_orders",
"(",
"self",
".",
"orderIDPrefix",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L148-L150 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.http_open_orders | (self) | return [o for o in orders if str(o['clOrdID']).startswith(self.orderIDPrefix)] | Get open orders via HTTP. Used on close to ensure we catch them all. | Get open orders via HTTP. Used on close to ensure we catch them all. | [
"Get",
"open",
"orders",
"via",
"HTTP",
".",
"Used",
"on",
"close",
"to",
"ensure",
"we",
"catch",
"them",
"all",
"."
] | def http_open_orders(self):
"""Get open orders via HTTP. Used on close to ensure we catch them all."""
api = "order"
orders = self._curl_bitmex(
api=api,
query={'filter': json.dumps({'ordStatus.isTerminated': False, 'symbol': self.symbol})},
verb="GET"
)
# Only return orders that start with our clOrdID prefix.
return [o for o in orders if str(o['clOrdID']).startswith(self.orderIDPrefix)] | [
"def",
"http_open_orders",
"(",
"self",
")",
":",
"api",
"=",
"\"order\"",
"orders",
"=",
"self",
".",
"_curl_bitmex",
"(",
"api",
"=",
"api",
",",
"query",
"=",
"{",
"'filter'",
":",
"json",
".",
"dumps",
"(",
"{",
"'ordStatus.isTerminated'",
":",
"False",
",",
"'symbol'",
":",
"self",
".",
"symbol",
"}",
")",
"}",
",",
"verb",
"=",
"\"GET\"",
")",
"# Only return orders that start with our clOrdID prefix.",
"return",
"[",
"o",
"for",
"o",
"in",
"orders",
"if",
"str",
"(",
"o",
"[",
"'clOrdID'",
"]",
")",
".",
"startswith",
"(",
"self",
".",
"orderIDPrefix",
")",
"]"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L153-L162 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX.cancel | (self, orderID) | return self._curl_bitmex(api=api, postdict=postdict, verb="DELETE") | Cancel an existing order. | Cancel an existing order. | [
"Cancel",
"an",
"existing",
"order",
"."
] | def cancel(self, orderID):
"""Cancel an existing order."""
api = "order"
postdict = {
'orderID': orderID,
}
return self._curl_bitmex(api=api, postdict=postdict, verb="DELETE") | [
"def",
"cancel",
"(",
"self",
",",
"orderID",
")",
":",
"api",
"=",
"\"order\"",
"postdict",
"=",
"{",
"'orderID'",
":",
"orderID",
",",
"}",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
"=",
"api",
",",
"postdict",
"=",
"postdict",
",",
"verb",
"=",
"\"DELETE\"",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L165-L171 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/bitmex.py | python | BitMEX._curl_bitmex | (self, api, query=None, postdict=None, timeout=3, verb=None, rethrow_errors=False) | return response.json() | Send a request to BitMEX Servers. | Send a request to BitMEX Servers. | [
"Send",
"a",
"request",
"to",
"BitMEX",
"Servers",
"."
] | def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None, rethrow_errors=False):
"""Send a request to BitMEX Servers."""
# Handle URL
url = self.base_url + api
# Default to POST if data is attached, GET otherwise
if not verb:
verb = 'POST' if postdict else 'GET'
# Auth: Use Access Token by default, API Key/Secret if provided
auth = AccessTokenAuth(self.token)
if self.apiKey:
auth = APIKeyAuthWithExpires(self.apiKey, self.apiSecret)
def maybe_exit(e):
if rethrow_errors:
raise e
else:
exit(1)
# Make the request
try:
req = requests.Request(verb, url, json=postdict, auth=auth, params=query)
prepped = self.session.prepare_request(req)
response = self.session.send(prepped, timeout=timeout)
# Make non-200s throw
response.raise_for_status()
except requests.exceptions.HTTPError as e:
# 401 - Auth error. This is fatal with API keys.
if response.status_code == 401:
self.logger.error("Login information or API Key incorrect, please check and restart.")
self.logger.error("Error: " + response.text)
if postdict:
self.logger.error(postdict)
# Always exit, even if rethrow_errors, because this is fatal
exit(1)
return self._curl_bitmex(api, query, postdict, timeout, verb)
# 404, can be thrown if order canceled does not exist.
elif response.status_code == 404:
if verb == 'DELETE':
self.logger.error("Order not found: %s" % postdict['orderID'])
return
self.logger.error("Unable to contact the BitMEX API (404). " +
"Request: %s \n %s" % (url, json.dumps(postdict)))
maybe_exit(e)
# 429, ratelimit
elif response.status_code == 429:
self.logger.error("Ratelimited on current request. Sleeping, then trying again. Try fewer " +
"order pairs or contact support@bitmex.com to raise your limits. " +
"Request: %s \n %s" % (url, json.dumps(postdict)))
sleep(1)
return self._curl_bitmex(api, query, postdict, timeout, verb)
# 503 - BitMEX temporary downtime, likely due to a deploy. Try again
elif response.status_code == 503:
self.logger.warning("Unable to contact the BitMEX API (503), retrying. " +
"Request: %s \n %s" % (url, json.dumps(postdict)))
sleep(1)
return self._curl_bitmex(api, query, postdict, timeout, verb)
# Duplicate clOrdID: that's fine, probably a deploy, go get the order and return it
elif (response.status_code == 400 and
response.json()['error'] and
response.json()['error']['message'] == 'Duplicate clOrdID'):
order = self._curl_bitmex('/order',
query={'filter': json.dumps({'clOrdID': postdict['clOrdID']})},
verb='GET')[0]
if (
order['orderQty'] != postdict['quantity'] or
order['price'] != postdict['price'] or
order['symbol'] != postdict['symbol']):
raise Exception('Attempted to recover from duplicate clOrdID, but order returned from API ' +
'did not match POST.\nPOST data: %s\nReturned order: %s' % (
json.dumps(postdict), json.dumps(order)))
# All good
return order
# Unknown Error
else:
self.logger.error("Unhandled Error: %s: %s" % (e, response.text))
self.logger.error("Endpoint was: %s %s: %s" % (verb, api, json.dumps(postdict)))
maybe_exit(e)
except requests.exceptions.Timeout as e:
# Timeout, re-run this request
self.logger.warning("Timed out, retrying...")
return self._curl_bitmex(api, query, postdict, timeout, verb)
except requests.exceptions.ConnectionError as e:
self.logger.warning("Unable to contact the BitMEX API (ConnectionError). Please check the URL. Retrying. " +
"Request: %s \n %s" % (url, json.dumps(postdict)))
sleep(1)
return self._curl_bitmex(api, query, postdict, timeout, verb)
return response.json() | [
"def",
"_curl_bitmex",
"(",
"self",
",",
"api",
",",
"query",
"=",
"None",
",",
"postdict",
"=",
"None",
",",
"timeout",
"=",
"3",
",",
"verb",
"=",
"None",
",",
"rethrow_errors",
"=",
"False",
")",
":",
"# Handle URL",
"url",
"=",
"self",
".",
"base_url",
"+",
"api",
"# Default to POST if data is attached, GET otherwise",
"if",
"not",
"verb",
":",
"verb",
"=",
"'POST'",
"if",
"postdict",
"else",
"'GET'",
"# Auth: Use Access Token by default, API Key/Secret if provided",
"auth",
"=",
"AccessTokenAuth",
"(",
"self",
".",
"token",
")",
"if",
"self",
".",
"apiKey",
":",
"auth",
"=",
"APIKeyAuthWithExpires",
"(",
"self",
".",
"apiKey",
",",
"self",
".",
"apiSecret",
")",
"def",
"maybe_exit",
"(",
"e",
")",
":",
"if",
"rethrow_errors",
":",
"raise",
"e",
"else",
":",
"exit",
"(",
"1",
")",
"# Make the request",
"try",
":",
"req",
"=",
"requests",
".",
"Request",
"(",
"verb",
",",
"url",
",",
"json",
"=",
"postdict",
",",
"auth",
"=",
"auth",
",",
"params",
"=",
"query",
")",
"prepped",
"=",
"self",
".",
"session",
".",
"prepare_request",
"(",
"req",
")",
"response",
"=",
"self",
".",
"session",
".",
"send",
"(",
"prepped",
",",
"timeout",
"=",
"timeout",
")",
"# Make non-200s throw",
"response",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"# 401 - Auth error. This is fatal with API keys.",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Login information or API Key incorrect, please check and restart.\"",
")",
"self",
".",
"logger",
".",
"error",
"(",
"\"Error: \"",
"+",
"response",
".",
"text",
")",
"if",
"postdict",
":",
"self",
".",
"logger",
".",
"error",
"(",
"postdict",
")",
"# Always exit, even if rethrow_errors, because this is fatal",
"exit",
"(",
"1",
")",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
",",
"query",
",",
"postdict",
",",
"timeout",
",",
"verb",
")",
"# 404, can be thrown if order canceled does not exist.",
"elif",
"response",
".",
"status_code",
"==",
"404",
":",
"if",
"verb",
"==",
"'DELETE'",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Order not found: %s\"",
"%",
"postdict",
"[",
"'orderID'",
"]",
")",
"return",
"self",
".",
"logger",
".",
"error",
"(",
"\"Unable to contact the BitMEX API (404). \"",
"+",
"\"Request: %s \\n %s\"",
"%",
"(",
"url",
",",
"json",
".",
"dumps",
"(",
"postdict",
")",
")",
")",
"maybe_exit",
"(",
"e",
")",
"# 429, ratelimit",
"elif",
"response",
".",
"status_code",
"==",
"429",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Ratelimited on current request. Sleeping, then trying again. Try fewer \"",
"+",
"\"order pairs or contact support@bitmex.com to raise your limits. \"",
"+",
"\"Request: %s \\n %s\"",
"%",
"(",
"url",
",",
"json",
".",
"dumps",
"(",
"postdict",
")",
")",
")",
"sleep",
"(",
"1",
")",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
",",
"query",
",",
"postdict",
",",
"timeout",
",",
"verb",
")",
"# 503 - BitMEX temporary downtime, likely due to a deploy. Try again",
"elif",
"response",
".",
"status_code",
"==",
"503",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Unable to contact the BitMEX API (503), retrying. \"",
"+",
"\"Request: %s \\n %s\"",
"%",
"(",
"url",
",",
"json",
".",
"dumps",
"(",
"postdict",
")",
")",
")",
"sleep",
"(",
"1",
")",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
",",
"query",
",",
"postdict",
",",
"timeout",
",",
"verb",
")",
"# Duplicate clOrdID: that's fine, probably a deploy, go get the order and return it",
"elif",
"(",
"response",
".",
"status_code",
"==",
"400",
"and",
"response",
".",
"json",
"(",
")",
"[",
"'error'",
"]",
"and",
"response",
".",
"json",
"(",
")",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"==",
"'Duplicate clOrdID'",
")",
":",
"order",
"=",
"self",
".",
"_curl_bitmex",
"(",
"'/order'",
",",
"query",
"=",
"{",
"'filter'",
":",
"json",
".",
"dumps",
"(",
"{",
"'clOrdID'",
":",
"postdict",
"[",
"'clOrdID'",
"]",
"}",
")",
"}",
",",
"verb",
"=",
"'GET'",
")",
"[",
"0",
"]",
"if",
"(",
"order",
"[",
"'orderQty'",
"]",
"!=",
"postdict",
"[",
"'quantity'",
"]",
"or",
"order",
"[",
"'price'",
"]",
"!=",
"postdict",
"[",
"'price'",
"]",
"or",
"order",
"[",
"'symbol'",
"]",
"!=",
"postdict",
"[",
"'symbol'",
"]",
")",
":",
"raise",
"Exception",
"(",
"'Attempted to recover from duplicate clOrdID, but order returned from API '",
"+",
"'did not match POST.\\nPOST data: %s\\nReturned order: %s'",
"%",
"(",
"json",
".",
"dumps",
"(",
"postdict",
")",
",",
"json",
".",
"dumps",
"(",
"order",
")",
")",
")",
"# All good",
"return",
"order",
"# Unknown Error",
"else",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Unhandled Error: %s: %s\"",
"%",
"(",
"e",
",",
"response",
".",
"text",
")",
")",
"self",
".",
"logger",
".",
"error",
"(",
"\"Endpoint was: %s %s: %s\"",
"%",
"(",
"verb",
",",
"api",
",",
"json",
".",
"dumps",
"(",
"postdict",
")",
")",
")",
"maybe_exit",
"(",
"e",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
"as",
"e",
":",
"# Timeout, re-run this request",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Timed out, retrying...\"",
")",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
",",
"query",
",",
"postdict",
",",
"timeout",
",",
"verb",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Unable to contact the BitMEX API (ConnectionError). Please check the URL. Retrying. \"",
"+",
"\"Request: %s \\n %s\"",
"%",
"(",
"url",
",",
"json",
".",
"dumps",
"(",
"postdict",
")",
")",
")",
"sleep",
"(",
"1",
")",
"return",
"self",
".",
"_curl_bitmex",
"(",
"api",
",",
"query",
",",
"postdict",
",",
"timeout",
",",
"verb",
")",
"return",
"response",
".",
"json",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/bitmex.py#L184-L282 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | ExchangeInterface.calc_delta | (self) | return delta | Calculate currency delta for portfolio | Calculate currency delta for portfolio | [
"Calculate",
"currency",
"delta",
"for",
"portfolio"
] | def calc_delta(self):
"""Calculate currency delta for portfolio"""
portfolio = self.get_portfolio()
spot_delta = 0
mark_delta = 0
for symbol in portfolio:
item = portfolio[symbol]
if item['futureType'] == "Quanto":
spot_delta += item['currentQty'] * item['multiplier'] * item['spot']
mark_delta += item['currentQty'] * item['multiplier'] * item['markPrice']
elif item['futureType'] == "Inverse":
spot_delta += (item['multiplier'] / item['spot']) * item['currentQty']
mark_delta += (item['multiplier'] / item['markPrice']) * item['currentQty']
basis_delta = mark_delta - spot_delta
delta = {
"spot": spot_delta,
"mark_price": mark_delta,
"basis": basis_delta
}
return delta | [
"def",
"calc_delta",
"(",
"self",
")",
":",
"portfolio",
"=",
"self",
".",
"get_portfolio",
"(",
")",
"spot_delta",
"=",
"0",
"mark_delta",
"=",
"0",
"for",
"symbol",
"in",
"portfolio",
":",
"item",
"=",
"portfolio",
"[",
"symbol",
"]",
"if",
"item",
"[",
"'futureType'",
"]",
"==",
"\"Quanto\"",
":",
"spot_delta",
"+=",
"item",
"[",
"'currentQty'",
"]",
"*",
"item",
"[",
"'multiplier'",
"]",
"*",
"item",
"[",
"'spot'",
"]",
"mark_delta",
"+=",
"item",
"[",
"'currentQty'",
"]",
"*",
"item",
"[",
"'multiplier'",
"]",
"*",
"item",
"[",
"'markPrice'",
"]",
"elif",
"item",
"[",
"'futureType'",
"]",
"==",
"\"Inverse\"",
":",
"spot_delta",
"+=",
"(",
"item",
"[",
"'multiplier'",
"]",
"/",
"item",
"[",
"'spot'",
"]",
")",
"*",
"item",
"[",
"'currentQty'",
"]",
"mark_delta",
"+=",
"(",
"item",
"[",
"'multiplier'",
"]",
"/",
"item",
"[",
"'markPrice'",
"]",
")",
"*",
"item",
"[",
"'currentQty'",
"]",
"basis_delta",
"=",
"mark_delta",
"-",
"spot_delta",
"delta",
"=",
"{",
"\"spot\"",
":",
"spot_delta",
",",
"\"mark_price\"",
":",
"mark_delta",
",",
"\"basis\"",
":",
"basis_delta",
"}",
"return",
"delta"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L95-L114 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | ExchangeInterface.is_open | (self) | return not self.bitmex.ws.exited | Check that websockets are still open. | Check that websockets are still open. | [
"Check",
"that",
"websockets",
"are",
"still",
"open",
"."
] | def is_open(self):
"""Check that websockets are still open."""
return not self.bitmex.ws.exited | [
"def",
"is_open",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"bitmex",
".",
"ws",
".",
"exited"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L165-L167 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | ExchangeInterface.check_if_orderbook_empty | (self) | This function checks whether the order book is empty | This function checks whether the order book is empty | [
"This",
"function",
"checks",
"whether",
"the",
"order",
"book",
"is",
"empty"
] | def check_if_orderbook_empty(self):
"""This function checks whether the order book is empty"""
instrument = self.get_instrument()
if instrument['midPrice'] is None:
raise errors.MarketEmptyError("Orderbook is empty, cannot quote")
sys.exit() | [
"def",
"check_if_orderbook_empty",
"(",
"self",
")",
":",
"instrument",
"=",
"self",
".",
"get_instrument",
"(",
")",
"if",
"instrument",
"[",
"'midPrice'",
"]",
"is",
"None",
":",
"raise",
"errors",
".",
"MarketEmptyError",
"(",
"\"Orderbook is empty, cannot quote\"",
")",
"sys",
".",
"exit",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L176-L181 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.print_status | (self) | Print the current MM status. | Print the current MM status. | [
"Print",
"the",
"current",
"MM",
"status",
"."
] | def print_status(self):
"""Print the current MM status."""
margin = self.exchange.get_margin()
position = self.exchange.get_position()
self.running_qty = self.exchange.get_delta()
self.start_XBt = margin["marginBalance"]
logger.info("Current XBT Balance: %.6f" % XBt_to_XBT(self.start_XBt))
logger.info("Current Contract Position: %d" % self.running_qty)
if settings.CHECK_POSITION_LIMITS:
logger.info("Position limits: %d/%d" % (settings.MIN_POSITION, settings.MAX_POSITION))
if position['currentQty'] != 0:
logger.info("Avg Cost Price: %.2f" % float(position['avgCostPrice']))
logger.info("Avg Entry Price: %.2f" % float(position['avgEntryPrice']))
logger.info("Contracts Traded This Run: %d" % (self.running_qty - self.starting_qty))
logger.info("Total Contract Delta: %.4f XBT" % self.exchange.calc_delta()['spot']) | [
"def",
"print_status",
"(",
"self",
")",
":",
"margin",
"=",
"self",
".",
"exchange",
".",
"get_margin",
"(",
")",
"position",
"=",
"self",
".",
"exchange",
".",
"get_position",
"(",
")",
"self",
".",
"running_qty",
"=",
"self",
".",
"exchange",
".",
"get_delta",
"(",
")",
"self",
".",
"start_XBt",
"=",
"margin",
"[",
"\"marginBalance\"",
"]",
"logger",
".",
"info",
"(",
"\"Current XBT Balance: %.6f\"",
"%",
"XBt_to_XBT",
"(",
"self",
".",
"start_XBt",
")",
")",
"logger",
".",
"info",
"(",
"\"Current Contract Position: %d\"",
"%",
"self",
".",
"running_qty",
")",
"if",
"settings",
".",
"CHECK_POSITION_LIMITS",
":",
"logger",
".",
"info",
"(",
"\"Position limits: %d/%d\"",
"%",
"(",
"settings",
".",
"MIN_POSITION",
",",
"settings",
".",
"MAX_POSITION",
")",
")",
"if",
"position",
"[",
"'currentQty'",
"]",
"!=",
"0",
":",
"logger",
".",
"info",
"(",
"\"Avg Cost Price: %.2f\"",
"%",
"float",
"(",
"position",
"[",
"'avgCostPrice'",
"]",
")",
")",
"logger",
".",
"info",
"(",
"\"Avg Entry Price: %.2f\"",
"%",
"float",
"(",
"position",
"[",
"'avgEntryPrice'",
"]",
")",
")",
"logger",
".",
"info",
"(",
"\"Contracts Traded This Run: %d\"",
"%",
"(",
"self",
".",
"running_qty",
"-",
"self",
".",
"starting_qty",
")",
")",
"logger",
".",
"info",
"(",
"\"Total Contract Delta: %.4f XBT\"",
"%",
"self",
".",
"exchange",
".",
"calc_delta",
"(",
")",
"[",
"'spot'",
"]",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L232-L248 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.get_price_offset | (self, index) | return round(start_position * (1 + settings.INTERVAL) ** index, self.instrument['tickLog']) | Given an index (1, -1, 2, -2, etc.) return the price for that side of the book.
Negative is a buy, positive is a sell. | Given an index (1, -1, 2, -2, etc.) return the price for that side of the book.
Negative is a buy, positive is a sell. | [
"Given",
"an",
"index",
"(",
"1",
"-",
"1",
"2",
"-",
"2",
"etc",
".",
")",
"return",
"the",
"price",
"for",
"that",
"side",
"of",
"the",
"book",
".",
"Negative",
"is",
"a",
"buy",
"positive",
"is",
"a",
"sell",
"."
] | def get_price_offset(self, index):
"""Given an index (1, -1, 2, -2, etc.) return the price for that side of the book.
Negative is a buy, positive is a sell."""
# Maintain existing spreads for max profit
if settings.MAINTAIN_SPREADS:
start_position = self.start_position_buy if index < 0 else self.start_position_sell
# First positions (index 1, -1) should start right at start_position, others should branch from there
index = index + 1 if index < 0 else index - 1
else:
# Offset mode: ticker comes from a reference exchange and we define an offset.
start_position = self.start_position_buy if index < 0 else self.start_position_sell
# If we're attempting to sell, but our sell price is actually lower than the buy,
# move over to the sell side.
if index > 0 and start_position < self.start_position_buy:
start_position = self.start_position_sell
# Same for buys.
if index < 0 and start_position > self.start_position_sell:
start_position = self.start_position_buy
return round(start_position * (1 + settings.INTERVAL) ** index, self.instrument['tickLog']) | [
"def",
"get_price_offset",
"(",
"self",
",",
"index",
")",
":",
"# Maintain existing spreads for max profit",
"if",
"settings",
".",
"MAINTAIN_SPREADS",
":",
"start_position",
"=",
"self",
".",
"start_position_buy",
"if",
"index",
"<",
"0",
"else",
"self",
".",
"start_position_sell",
"# First positions (index 1, -1) should start right at start_position, others should branch from there",
"index",
"=",
"index",
"+",
"1",
"if",
"index",
"<",
"0",
"else",
"index",
"-",
"1",
"else",
":",
"# Offset mode: ticker comes from a reference exchange and we define an offset.",
"start_position",
"=",
"self",
".",
"start_position_buy",
"if",
"index",
"<",
"0",
"else",
"self",
".",
"start_position_sell",
"# If we're attempting to sell, but our sell price is actually lower than the buy,",
"# move over to the sell side.",
"if",
"index",
">",
"0",
"and",
"start_position",
"<",
"self",
".",
"start_position_buy",
":",
"start_position",
"=",
"self",
".",
"start_position_sell",
"# Same for buys.",
"if",
"index",
"<",
"0",
"and",
"start_position",
">",
"self",
".",
"start_position_sell",
":",
"start_position",
"=",
"self",
".",
"start_position_buy",
"return",
"round",
"(",
"start_position",
"*",
"(",
"1",
"+",
"settings",
".",
"INTERVAL",
")",
"**",
"index",
",",
"self",
".",
"instrument",
"[",
"'tickLog'",
"]",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L299-L319 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.place_orders | (self) | return self.converge_orders(buy_orders, sell_orders) | Create order items for use in convergence. | Create order items for use in convergence. | [
"Create",
"order",
"items",
"for",
"use",
"in",
"convergence",
"."
] | def place_orders(self):
"""Create order items for use in convergence."""
buy_orders = []
sell_orders = []
# Create orders from the outside in. This is intentional - let's say the inner order gets taken;
# then we match orders from the outside in, ensuring the fewest number of orders are amended and only
# a new order is created in the inside. If we did it inside-out, all orders would be amended
# down and a new order would be created at the outside.
if self.enough_liquidity():
for i in reversed(range(1, settings.ORDER_PAIRS + 1)):
if not self.long_position_limit_exceeded():
buy_orders.append(self.prepare_order(-i))
if not self.short_position_limit_exceeded():
sell_orders.append(self.prepare_order(i))
return self.converge_orders(buy_orders, sell_orders) | [
"def",
"place_orders",
"(",
"self",
")",
":",
"buy_orders",
"=",
"[",
"]",
"sell_orders",
"=",
"[",
"]",
"# Create orders from the outside in. This is intentional - let's say the inner order gets taken;",
"# then we match orders from the outside in, ensuring the fewest number of orders are amended and only",
"# a new order is created in the inside. If we did it inside-out, all orders would be amended",
"# down and a new order would be created at the outside.",
"if",
"self",
".",
"enough_liquidity",
"(",
")",
":",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"1",
",",
"settings",
".",
"ORDER_PAIRS",
"+",
"1",
")",
")",
":",
"if",
"not",
"self",
".",
"long_position_limit_exceeded",
"(",
")",
":",
"buy_orders",
".",
"append",
"(",
"self",
".",
"prepare_order",
"(",
"-",
"i",
")",
")",
"if",
"not",
"self",
".",
"short_position_limit_exceeded",
"(",
")",
":",
"sell_orders",
".",
"append",
"(",
"self",
".",
"prepare_order",
"(",
"i",
")",
")",
"return",
"self",
".",
"converge_orders",
"(",
"buy_orders",
",",
"sell_orders",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L325-L341 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.prepare_order | (self, index) | return {'price': price, 'orderQty': quantity, 'side': "Buy" if index < 0 else "Sell"} | Create an order object. | Create an order object. | [
"Create",
"an",
"order",
"object",
"."
] | def prepare_order(self, index):
"""Create an order object."""
if settings.RANDOM_ORDER_SIZE is True:
quantity = random.randint(settings.MIN_ORDER_SIZE, settings.MAX_ORDER_SIZE)
else:
quantity = settings.ORDER_START_SIZE + ((abs(index) - 1) * settings.ORDER_STEP_SIZE)
price = self.get_price_offset(index)
return {'price': price, 'orderQty': quantity, 'side': "Buy" if index < 0 else "Sell"} | [
"def",
"prepare_order",
"(",
"self",
",",
"index",
")",
":",
"if",
"settings",
".",
"RANDOM_ORDER_SIZE",
"is",
"True",
":",
"quantity",
"=",
"random",
".",
"randint",
"(",
"settings",
".",
"MIN_ORDER_SIZE",
",",
"settings",
".",
"MAX_ORDER_SIZE",
")",
"else",
":",
"quantity",
"=",
"settings",
".",
"ORDER_START_SIZE",
"+",
"(",
"(",
"abs",
"(",
"index",
")",
"-",
"1",
")",
"*",
"settings",
".",
"ORDER_STEP_SIZE",
")",
"price",
"=",
"self",
".",
"get_price_offset",
"(",
"index",
")",
"return",
"{",
"'price'",
":",
"price",
",",
"'orderQty'",
":",
"quantity",
",",
"'side'",
":",
"\"Buy\"",
"if",
"index",
"<",
"0",
"else",
"\"Sell\"",
"}"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L343-L353 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.converge_orders | (self, buy_orders, sell_orders) | Converge the orders we currently have in the book with what we want to be in the book.
This involves amending any open orders and creating new ones if any have filled completely.
We start from the closest orders outward. | Converge the orders we currently have in the book with what we want to be in the book.
This involves amending any open orders and creating new ones if any have filled completely.
We start from the closest orders outward. | [
"Converge",
"the",
"orders",
"we",
"currently",
"have",
"in",
"the",
"book",
"with",
"what",
"we",
"want",
"to",
"be",
"in",
"the",
"book",
".",
"This",
"involves",
"amending",
"any",
"open",
"orders",
"and",
"creating",
"new",
"ones",
"if",
"any",
"have",
"filled",
"completely",
".",
"We",
"start",
"from",
"the",
"closest",
"orders",
"outward",
"."
] | def converge_orders(self, buy_orders, sell_orders):
"""Converge the orders we currently have in the book with what we want to be in the book.
This involves amending any open orders and creating new ones if any have filled completely.
We start from the closest orders outward."""
tickLog = self.exchange.get_instrument()['tickLog']
to_amend = []
to_create = []
to_cancel = []
buys_matched = 0
sells_matched = 0
existing_orders = self.exchange.get_orders()
# Check all existing orders and match them up with what we want to place.
# If there's an open one, we might be able to amend it to fit what we want.
for order in existing_orders:
try:
if order['side'] == 'Buy':
desired_order = buy_orders[buys_matched]
buys_matched += 1
else:
desired_order = sell_orders[sells_matched]
sells_matched += 1
# Found an existing order. Do we need to amend it?
if desired_order['orderQty'] != order['leavesQty'] or (
# If price has changed, and the change is more than our RELIST_INTERVAL, amend.
desired_order['price'] != order['price'] and
abs((desired_order['price'] / order['price']) - 1) > settings.RELIST_INTERVAL):
to_amend.append({'orderID': order['orderID'], 'leavesQty': desired_order['orderQty'],
'price': desired_order['price'], 'side': order['side']})
except IndexError:
# Will throw if there isn't a desired order to match. In that case, cancel it.
to_cancel.append(order)
while buys_matched < len(buy_orders):
to_create.append(buy_orders[buys_matched])
buys_matched += 1
while sells_matched < len(sell_orders):
to_create.append(sell_orders[sells_matched])
sells_matched += 1
if len(to_amend) > 0:
for amended_order in reversed(to_amend):
reference_order = [o for o in existing_orders if o['orderID'] == amended_order['orderID']][0]
logger.info("Amending %4s: %d @ %.*f to %d @ %.*f (%+.*f)" % (
amended_order['side'],
reference_order['leavesQty'], tickLog, reference_order['price'],
amended_order['leavesQty'], tickLog, amended_order['price'],
tickLog, (amended_order['price'] - reference_order['price'])
))
# This can fail if an order has closed in the time we were processing.
# The API will send us `invalid ordStatus`, which means that the order's status (Filled/Canceled)
# made it not amendable.
# If that happens, we need to catch it and re-tick.
try:
self.exchange.amend_bulk_orders(to_amend)
except requests.exceptions.HTTPError as e:
errorObj = e.response.json()
if errorObj['error']['message'] == 'Invalid ordStatus':
logger.warn("Amending failed. Waiting for order data to converge and retrying.")
sleep(0.5)
return self.place_orders()
else:
logger.error("Unknown error on amend: %s. Exiting" % errorObj)
sys.exit(1)
if len(to_create) > 0:
logger.info("Creating %d orders:" % (len(to_create)))
for order in reversed(to_create):
logger.info("%4s %d @ %.*f" % (order['side'], order['orderQty'], tickLog, order['price']))
self.exchange.create_bulk_orders(to_create)
# Could happen if we exceed a delta limit
if len(to_cancel) > 0:
logger.info("Canceling %d orders:" % (len(to_cancel)))
for order in reversed(to_cancel):
logger.info("%4s %d @ %.*f" % (order['side'], order['leavesQty'], tickLog, order['price']))
self.exchange.cancel_bulk_orders(to_cancel) | [
"def",
"converge_orders",
"(",
"self",
",",
"buy_orders",
",",
"sell_orders",
")",
":",
"tickLog",
"=",
"self",
".",
"exchange",
".",
"get_instrument",
"(",
")",
"[",
"'tickLog'",
"]",
"to_amend",
"=",
"[",
"]",
"to_create",
"=",
"[",
"]",
"to_cancel",
"=",
"[",
"]",
"buys_matched",
"=",
"0",
"sells_matched",
"=",
"0",
"existing_orders",
"=",
"self",
".",
"exchange",
".",
"get_orders",
"(",
")",
"# Check all existing orders and match them up with what we want to place.",
"# If there's an open one, we might be able to amend it to fit what we want.",
"for",
"order",
"in",
"existing_orders",
":",
"try",
":",
"if",
"order",
"[",
"'side'",
"]",
"==",
"'Buy'",
":",
"desired_order",
"=",
"buy_orders",
"[",
"buys_matched",
"]",
"buys_matched",
"+=",
"1",
"else",
":",
"desired_order",
"=",
"sell_orders",
"[",
"sells_matched",
"]",
"sells_matched",
"+=",
"1",
"# Found an existing order. Do we need to amend it?",
"if",
"desired_order",
"[",
"'orderQty'",
"]",
"!=",
"order",
"[",
"'leavesQty'",
"]",
"or",
"(",
"# If price has changed, and the change is more than our RELIST_INTERVAL, amend.",
"desired_order",
"[",
"'price'",
"]",
"!=",
"order",
"[",
"'price'",
"]",
"and",
"abs",
"(",
"(",
"desired_order",
"[",
"'price'",
"]",
"/",
"order",
"[",
"'price'",
"]",
")",
"-",
"1",
")",
">",
"settings",
".",
"RELIST_INTERVAL",
")",
":",
"to_amend",
".",
"append",
"(",
"{",
"'orderID'",
":",
"order",
"[",
"'orderID'",
"]",
",",
"'leavesQty'",
":",
"desired_order",
"[",
"'orderQty'",
"]",
",",
"'price'",
":",
"desired_order",
"[",
"'price'",
"]",
",",
"'side'",
":",
"order",
"[",
"'side'",
"]",
"}",
")",
"except",
"IndexError",
":",
"# Will throw if there isn't a desired order to match. In that case, cancel it.",
"to_cancel",
".",
"append",
"(",
"order",
")",
"while",
"buys_matched",
"<",
"len",
"(",
"buy_orders",
")",
":",
"to_create",
".",
"append",
"(",
"buy_orders",
"[",
"buys_matched",
"]",
")",
"buys_matched",
"+=",
"1",
"while",
"sells_matched",
"<",
"len",
"(",
"sell_orders",
")",
":",
"to_create",
".",
"append",
"(",
"sell_orders",
"[",
"sells_matched",
"]",
")",
"sells_matched",
"+=",
"1",
"if",
"len",
"(",
"to_amend",
")",
">",
"0",
":",
"for",
"amended_order",
"in",
"reversed",
"(",
"to_amend",
")",
":",
"reference_order",
"=",
"[",
"o",
"for",
"o",
"in",
"existing_orders",
"if",
"o",
"[",
"'orderID'",
"]",
"==",
"amended_order",
"[",
"'orderID'",
"]",
"]",
"[",
"0",
"]",
"logger",
".",
"info",
"(",
"\"Amending %4s: %d @ %.*f to %d @ %.*f (%+.*f)\"",
"%",
"(",
"amended_order",
"[",
"'side'",
"]",
",",
"reference_order",
"[",
"'leavesQty'",
"]",
",",
"tickLog",
",",
"reference_order",
"[",
"'price'",
"]",
",",
"amended_order",
"[",
"'leavesQty'",
"]",
",",
"tickLog",
",",
"amended_order",
"[",
"'price'",
"]",
",",
"tickLog",
",",
"(",
"amended_order",
"[",
"'price'",
"]",
"-",
"reference_order",
"[",
"'price'",
"]",
")",
")",
")",
"# This can fail if an order has closed in the time we were processing.",
"# The API will send us `invalid ordStatus`, which means that the order's status (Filled/Canceled)",
"# made it not amendable.",
"# If that happens, we need to catch it and re-tick.",
"try",
":",
"self",
".",
"exchange",
".",
"amend_bulk_orders",
"(",
"to_amend",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"errorObj",
"=",
"e",
".",
"response",
".",
"json",
"(",
")",
"if",
"errorObj",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"==",
"'Invalid ordStatus'",
":",
"logger",
".",
"warn",
"(",
"\"Amending failed. Waiting for order data to converge and retrying.\"",
")",
"sleep",
"(",
"0.5",
")",
"return",
"self",
".",
"place_orders",
"(",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"Unknown error on amend: %s. Exiting\"",
"%",
"errorObj",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"len",
"(",
"to_create",
")",
">",
"0",
":",
"logger",
".",
"info",
"(",
"\"Creating %d orders:\"",
"%",
"(",
"len",
"(",
"to_create",
")",
")",
")",
"for",
"order",
"in",
"reversed",
"(",
"to_create",
")",
":",
"logger",
".",
"info",
"(",
"\"%4s %d @ %.*f\"",
"%",
"(",
"order",
"[",
"'side'",
"]",
",",
"order",
"[",
"'orderQty'",
"]",
",",
"tickLog",
",",
"order",
"[",
"'price'",
"]",
")",
")",
"self",
".",
"exchange",
".",
"create_bulk_orders",
"(",
"to_create",
")",
"# Could happen if we exceed a delta limit",
"if",
"len",
"(",
"to_cancel",
")",
">",
"0",
":",
"logger",
".",
"info",
"(",
"\"Canceling %d orders:\"",
"%",
"(",
"len",
"(",
"to_cancel",
")",
")",
")",
"for",
"order",
"in",
"reversed",
"(",
"to_cancel",
")",
":",
"logger",
".",
"info",
"(",
"\"%4s %d @ %.*f\"",
"%",
"(",
"order",
"[",
"'side'",
"]",
",",
"order",
"[",
"'leavesQty'",
"]",
",",
"tickLog",
",",
"order",
"[",
"'price'",
"]",
")",
")",
"self",
".",
"exchange",
".",
"cancel_bulk_orders",
"(",
"to_cancel",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L355-L434 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.short_position_limit_exceeded | (self) | return position <= settings.MIN_POSITION | Returns True if the short position limit is exceeded | Returns True if the short position limit is exceeded | [
"Returns",
"True",
"if",
"the",
"short",
"position",
"limit",
"is",
"exceeded"
] | def short_position_limit_exceeded(self):
"Returns True if the short position limit is exceeded"
if not settings.CHECK_POSITION_LIMITS:
return False
position = self.exchange.get_delta()
return position <= settings.MIN_POSITION | [
"def",
"short_position_limit_exceeded",
"(",
"self",
")",
":",
"if",
"not",
"settings",
".",
"CHECK_POSITION_LIMITS",
":",
"return",
"False",
"position",
"=",
"self",
".",
"exchange",
".",
"get_delta",
"(",
")",
"return",
"position",
"<=",
"settings",
".",
"MIN_POSITION"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L440-L445 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.long_position_limit_exceeded | (self) | return position >= settings.MAX_POSITION | Returns True if the long position limit is exceeded | Returns True if the long position limit is exceeded | [
"Returns",
"True",
"if",
"the",
"long",
"position",
"limit",
"is",
"exceeded"
] | def long_position_limit_exceeded(self):
"Returns True if the long position limit is exceeded"
if not settings.CHECK_POSITION_LIMITS:
return False
position = self.exchange.get_delta()
return position >= settings.MAX_POSITION | [
"def",
"long_position_limit_exceeded",
"(",
"self",
")",
":",
"if",
"not",
"settings",
".",
"CHECK_POSITION_LIMITS",
":",
"return",
"False",
"position",
"=",
"self",
".",
"exchange",
".",
"get_delta",
"(",
")",
"return",
"position",
">=",
"settings",
".",
"MAX_POSITION"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L447-L452 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.enough_liquidity | (self) | return enough_liquidity | Returns true if there is enough liquidity on each side of the order book | Returns true if there is enough liquidity on each side of the order book | [
"Returns",
"true",
"if",
"there",
"is",
"enough",
"liquidity",
"on",
"each",
"side",
"of",
"the",
"order",
"book"
] | def enough_liquidity(self):
"Returns true if there is enough liquidity on each side of the order book"
enough_liquidity = False
ticker = self.exchange.get_ticker()
order_book = self.exchange.market_depth()
highest_buy = self.exchange.get_highest_buy()
lowest_sell = self.exchange.get_lowest_sell()
bid_depth = sum([x["bidSize"] for x in filter(lambda x: x["bidSize"]!=None, order_book)])
ask_depth = sum([x["askSize"] for x in filter(lambda x: x["askSize"]!=None, order_book)])
bid_liquid = bid_depth - highest_buy["orderQty"]
logger.info("Bid Liquidity: "+str(bid_liquid)+" Contracts")
ask_liquid = ask_depth - lowest_sell["orderQty"]
logger.info("Ask Liquidity: "+str(ask_liquid)+" Contracts")
enough_ask_liquidity = ask_liquid >= settings.MIN_CONTRACTS
enough_bid_liquidity = bid_liquid >= settings.MIN_CONTRACTS
enough_liquidity = (enough_ask_liquidity and enough_bid_liquidity)
if not enough_liquidity:
if (not enough_bid_liquidity) and (not enough_ask_liquidity):
logger.info("Neither side has enough liquidity")
elif not enough_bid_liquidity:
logger.info("Bid side is not liquid enough")
else:
logger.info("Ask side is not liquid enough")
return enough_liquidity | [
"def",
"enough_liquidity",
"(",
"self",
")",
":",
"enough_liquidity",
"=",
"False",
"ticker",
"=",
"self",
".",
"exchange",
".",
"get_ticker",
"(",
")",
"order_book",
"=",
"self",
".",
"exchange",
".",
"market_depth",
"(",
")",
"highest_buy",
"=",
"self",
".",
"exchange",
".",
"get_highest_buy",
"(",
")",
"lowest_sell",
"=",
"self",
".",
"exchange",
".",
"get_lowest_sell",
"(",
")",
"bid_depth",
"=",
"sum",
"(",
"[",
"x",
"[",
"\"bidSize\"",
"]",
"for",
"x",
"in",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"\"bidSize\"",
"]",
"!=",
"None",
",",
"order_book",
")",
"]",
")",
"ask_depth",
"=",
"sum",
"(",
"[",
"x",
"[",
"\"askSize\"",
"]",
"for",
"x",
"in",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"\"askSize\"",
"]",
"!=",
"None",
",",
"order_book",
")",
"]",
")",
"bid_liquid",
"=",
"bid_depth",
"-",
"highest_buy",
"[",
"\"orderQty\"",
"]",
"logger",
".",
"info",
"(",
"\"Bid Liquidity: \"",
"+",
"str",
"(",
"bid_liquid",
")",
"+",
"\" Contracts\"",
")",
"ask_liquid",
"=",
"ask_depth",
"-",
"lowest_sell",
"[",
"\"orderQty\"",
"]",
"logger",
".",
"info",
"(",
"\"Ask Liquidity: \"",
"+",
"str",
"(",
"ask_liquid",
")",
"+",
"\" Contracts\"",
")",
"enough_ask_liquidity",
"=",
"ask_liquid",
">=",
"settings",
".",
"MIN_CONTRACTS",
"enough_bid_liquidity",
"=",
"bid_liquid",
">=",
"settings",
".",
"MIN_CONTRACTS",
"enough_liquidity",
"=",
"(",
"enough_ask_liquidity",
"and",
"enough_bid_liquidity",
")",
"if",
"not",
"enough_liquidity",
":",
"if",
"(",
"not",
"enough_bid_liquidity",
")",
"and",
"(",
"not",
"enough_ask_liquidity",
")",
":",
"logger",
".",
"info",
"(",
"\"Neither side has enough liquidity\"",
")",
"elif",
"not",
"enough_bid_liquidity",
":",
"logger",
".",
"info",
"(",
"\"Bid side is not liquid enough\"",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"Ask side is not liquid enough\"",
")",
"return",
"enough_liquidity"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L457-L482 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.sanity_check | (self) | Perform checks before placing orders. | Perform checks before placing orders. | [
"Perform",
"checks",
"before",
"placing",
"orders",
"."
] | def sanity_check(self):
"""Perform checks before placing orders."""
# Check if OB is empty - if so, can't quote.
self.exchange.check_if_orderbook_empty()
# Ensure market is still open.
self.exchange.check_market_open()
# Get ticker, which sets price offsets and prints some debugging info.
ticker = self.get_ticker()
# Sanity check:
if self.get_price_offset(-1) >= ticker["sell"] or self.get_price_offset(1) <= ticker["buy"]:
logger.error(self.start_position_buy, self.start_position_sell)
logger.error("%s %s %s %s" % (self.get_price_offset(-1), ticker["sell"], self.get_price_offset(1), ticker["buy"]))
logger.error("Sanity check failed, exchange data is inconsistent")
sys.exit()
# Messanging if the position limits are reached
if self.long_position_limit_exceeded():
logger.info("Long delta limit exceeded")
logger.info("Current Position: %.f, Maximum Position: %.f" %
(self.exchange.get_delta(), settings.MAX_POSITION))
if self.short_position_limit_exceeded():
logger.info("Short delta limit exceeded")
logger.info("Current Position: %.f, Minimum Position: %.f" %
(self.exchange.get_delta(), settings.MIN_POSITION)) | [
"def",
"sanity_check",
"(",
"self",
")",
":",
"# Check if OB is empty - if so, can't quote.",
"self",
".",
"exchange",
".",
"check_if_orderbook_empty",
"(",
")",
"# Ensure market is still open.",
"self",
".",
"exchange",
".",
"check_market_open",
"(",
")",
"# Get ticker, which sets price offsets and prints some debugging info.",
"ticker",
"=",
"self",
".",
"get_ticker",
"(",
")",
"# Sanity check:",
"if",
"self",
".",
"get_price_offset",
"(",
"-",
"1",
")",
">=",
"ticker",
"[",
"\"sell\"",
"]",
"or",
"self",
".",
"get_price_offset",
"(",
"1",
")",
"<=",
"ticker",
"[",
"\"buy\"",
"]",
":",
"logger",
".",
"error",
"(",
"self",
".",
"start_position_buy",
",",
"self",
".",
"start_position_sell",
")",
"logger",
".",
"error",
"(",
"\"%s %s %s %s\"",
"%",
"(",
"self",
".",
"get_price_offset",
"(",
"-",
"1",
")",
",",
"ticker",
"[",
"\"sell\"",
"]",
",",
"self",
".",
"get_price_offset",
"(",
"1",
")",
",",
"ticker",
"[",
"\"buy\"",
"]",
")",
")",
"logger",
".",
"error",
"(",
"\"Sanity check failed, exchange data is inconsistent\"",
")",
"sys",
".",
"exit",
"(",
")",
"# Messanging if the position limits are reached",
"if",
"self",
".",
"long_position_limit_exceeded",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Long delta limit exceeded\"",
")",
"logger",
".",
"info",
"(",
"\"Current Position: %.f, Maximum Position: %.f\"",
"%",
"(",
"self",
".",
"exchange",
".",
"get_delta",
"(",
")",
",",
"settings",
".",
"MAX_POSITION",
")",
")",
"if",
"self",
".",
"short_position_limit_exceeded",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Short delta limit exceeded\"",
")",
"logger",
".",
"info",
"(",
"\"Current Position: %.f, Minimum Position: %.f\"",
"%",
"(",
"self",
".",
"exchange",
".",
"get_delta",
"(",
")",
",",
"settings",
".",
"MIN_POSITION",
")",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L488-L516 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.check_file_change | (self) | Restart if any files we're watching have changed. | Restart if any files we're watching have changed. | [
"Restart",
"if",
"any",
"files",
"we",
"re",
"watching",
"have",
"changed",
"."
] | def check_file_change(self):
"""Restart if any files we're watching have changed."""
for f, mtime in watched_files_mtimes:
if getmtime(f) > mtime:
self.restart() | [
"def",
"check_file_change",
"(",
"self",
")",
":",
"for",
"f",
",",
"mtime",
"in",
"watched_files_mtimes",
":",
"if",
"getmtime",
"(",
"f",
")",
">",
"mtime",
":",
"self",
".",
"restart",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L522-L526 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/market_maker.py | python | OrderManager.check_connection | (self) | return self.exchange.is_open() | Ensure the WS connections are still open. | Ensure the WS connections are still open. | [
"Ensure",
"the",
"WS",
"connections",
"are",
"still",
"open",
"."
] | def check_connection(self):
"""Ensure the WS connections are still open."""
return self.exchange.is_open() | [
"def",
"check_connection",
"(",
"self",
")",
":",
"return",
"self",
".",
"exchange",
".",
"is_open",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/market_maker.py#L528-L530 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/settings.py | python | import_path | (fullpath) | return module | Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do. | Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do. | [
"Import",
"a",
"file",
"with",
"full",
"path",
"specification",
".",
"Allows",
"one",
"to",
"import",
"from",
"anywhere",
"something",
"__import__",
"does",
"not",
"do",
"."
] | def import_path(fullpath):
"""
Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.insert(0, path)
module = __import__(filename)
reload(module) # Might be out of date
del sys.path[0]
return module | [
"def",
"import_path",
"(",
"fullpath",
")",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fullpath",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"path",
")",
"module",
"=",
"__import__",
"(",
"filename",
")",
"reload",
"(",
"module",
")",
"# Might be out of date",
"del",
"sys",
".",
"path",
"[",
"0",
"]",
"return",
"module"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/settings.py#L9-L20 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.connect | (self, endpoint="", symbol="XBTN15", shouldAuth=True) | Connect to the websocket and initialize data stores. | Connect to the websocket and initialize data stores. | [
"Connect",
"to",
"the",
"websocket",
"and",
"initialize",
"data",
"stores",
"."
] | def connect(self, endpoint="", symbol="XBTN15", shouldAuth=True):
'''Connect to the websocket and initialize data stores.'''
self.logger.debug("Connecting WebSocket.")
self.symbol = symbol
self.shouldAuth = shouldAuth
# We can subscribe right in the connection querystring, so let's build that.
# Subscribe to all pertinent endpoints
subscriptions = [sub + ':' + symbol for sub in ["quote", "trade", "orderBook25"]]
subscriptions += ["instrument"] # We want all of them
if self.shouldAuth:
subscriptions += [sub + ':' + symbol for sub in ["order", "execution"]]
subscriptions += ["margin", "position"]
# Get WS URL and connect.
urlParts = list(urlparse(endpoint))
urlParts[0] = urlParts[0].replace('http', 'ws')
urlParts[2] = "/realtime?subscribe=" + ",".join(subscriptions)
wsURL = urlunparse(urlParts)
self.logger.info("Connecting to %s" % wsURL)
self.__connect(wsURL)
self.logger.info('Connected to WS. Waiting for data images, this may take a moment...')
# Connected. Wait for partials
self.__wait_for_symbol(symbol)
if self.shouldAuth:
self.__wait_for_account()
self.logger.info('Got all market data. Starting.') | [
"def",
"connect",
"(",
"self",
",",
"endpoint",
"=",
"\"\"",
",",
"symbol",
"=",
"\"XBTN15\"",
",",
"shouldAuth",
"=",
"True",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Connecting WebSocket.\"",
")",
"self",
".",
"symbol",
"=",
"symbol",
"self",
".",
"shouldAuth",
"=",
"shouldAuth",
"# We can subscribe right in the connection querystring, so let's build that.",
"# Subscribe to all pertinent endpoints",
"subscriptions",
"=",
"[",
"sub",
"+",
"':'",
"+",
"symbol",
"for",
"sub",
"in",
"[",
"\"quote\"",
",",
"\"trade\"",
",",
"\"orderBook25\"",
"]",
"]",
"subscriptions",
"+=",
"[",
"\"instrument\"",
"]",
"# We want all of them",
"if",
"self",
".",
"shouldAuth",
":",
"subscriptions",
"+=",
"[",
"sub",
"+",
"':'",
"+",
"symbol",
"for",
"sub",
"in",
"[",
"\"order\"",
",",
"\"execution\"",
"]",
"]",
"subscriptions",
"+=",
"[",
"\"margin\"",
",",
"\"position\"",
"]",
"# Get WS URL and connect.",
"urlParts",
"=",
"list",
"(",
"urlparse",
"(",
"endpoint",
")",
")",
"urlParts",
"[",
"0",
"]",
"=",
"urlParts",
"[",
"0",
"]",
".",
"replace",
"(",
"'http'",
",",
"'ws'",
")",
"urlParts",
"[",
"2",
"]",
"=",
"\"/realtime?subscribe=\"",
"+",
"\",\"",
".",
"join",
"(",
"subscriptions",
")",
"wsURL",
"=",
"urlunparse",
"(",
"urlParts",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Connecting to %s\"",
"%",
"wsURL",
")",
"self",
".",
"__connect",
"(",
"wsURL",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Connected to WS. Waiting for data images, this may take a moment...'",
")",
"# Connected. Wait for partials",
"self",
".",
"__wait_for_symbol",
"(",
"symbol",
")",
"if",
"self",
".",
"shouldAuth",
":",
"self",
".",
"__wait_for_account",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Got all market data. Starting.'",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L34-L62 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.get_ticker | (self, symbol) | return {k: round(float(v or 0), instrument['tickLog']) for k, v in iteritems(ticker)} | Return a ticker object. Generated from instrument. | Return a ticker object. Generated from instrument. | [
"Return",
"a",
"ticker",
"object",
".",
"Generated",
"from",
"instrument",
"."
] | def get_ticker(self, symbol):
'''Return a ticker object. Generated from instrument.'''
instrument = self.get_instrument(symbol)
# If this is an index, we have to get the data from the last trade.
if instrument['symbol'][0] == '.':
ticker = {}
ticker['mid'] = ticker['buy'] = ticker['sell'] = ticker['last'] = instrument['markPrice']
# Normal instrument
else:
bid = instrument['bidPrice'] or instrument['lastPrice']
ask = instrument['askPrice'] or instrument['lastPrice']
ticker = {
"last": instrument['lastPrice'],
"buy": bid,
"sell": ask,
"mid": (bid + ask) / 2
}
# The instrument has a tickSize. Use it to round values.
return {k: round(float(v or 0), instrument['tickLog']) for k, v in iteritems(ticker)} | [
"def",
"get_ticker",
"(",
"self",
",",
"symbol",
")",
":",
"instrument",
"=",
"self",
".",
"get_instrument",
"(",
"symbol",
")",
"# If this is an index, we have to get the data from the last trade.",
"if",
"instrument",
"[",
"'symbol'",
"]",
"[",
"0",
"]",
"==",
"'.'",
":",
"ticker",
"=",
"{",
"}",
"ticker",
"[",
"'mid'",
"]",
"=",
"ticker",
"[",
"'buy'",
"]",
"=",
"ticker",
"[",
"'sell'",
"]",
"=",
"ticker",
"[",
"'last'",
"]",
"=",
"instrument",
"[",
"'markPrice'",
"]",
"# Normal instrument",
"else",
":",
"bid",
"=",
"instrument",
"[",
"'bidPrice'",
"]",
"or",
"instrument",
"[",
"'lastPrice'",
"]",
"ask",
"=",
"instrument",
"[",
"'askPrice'",
"]",
"or",
"instrument",
"[",
"'lastPrice'",
"]",
"ticker",
"=",
"{",
"\"last\"",
":",
"instrument",
"[",
"'lastPrice'",
"]",
",",
"\"buy\"",
":",
"bid",
",",
"\"sell\"",
":",
"ask",
",",
"\"mid\"",
":",
"(",
"bid",
"+",
"ask",
")",
"/",
"2",
"}",
"# The instrument has a tickSize. Use it to round values.",
"return",
"{",
"k",
":",
"round",
"(",
"float",
"(",
"v",
"or",
"0",
")",
",",
"instrument",
"[",
"'tickLog'",
"]",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"ticker",
")",
"}"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L78-L99 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.__connect | (self, wsURL) | Connect to the websocket in a thread. | Connect to the websocket in a thread. | [
"Connect",
"to",
"the",
"websocket",
"in",
"a",
"thread",
"."
] | def __connect(self, wsURL):
'''Connect to the websocket in a thread.'''
self.logger.debug("Starting thread")
self.ws = websocket.WebSocketApp(wsURL,
on_message=self.__on_message,
on_close=self.__on_close,
on_open=self.__on_open,
on_error=self.__on_error,
# We can login using email/pass or API key
header=self.__get_auth())
self.wst = threading.Thread(target=lambda: self.ws.run_forever())
self.wst.daemon = True
self.wst.start()
self.logger.info("Started thread")
# Wait for connect before continuing
conn_timeout = 5
while (not self.ws.sock or not self.ws.sock.connected) and conn_timeout and not self._error:
sleep(1)
conn_timeout -= 1
if not conn_timeout or self._error:
self.logger.error("Couldn't connect to WS! Exiting.")
self.exit()
sys.exit(1) | [
"def",
"__connect",
"(",
"self",
",",
"wsURL",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Starting thread\"",
")",
"self",
".",
"ws",
"=",
"websocket",
".",
"WebSocketApp",
"(",
"wsURL",
",",
"on_message",
"=",
"self",
".",
"__on_message",
",",
"on_close",
"=",
"self",
".",
"__on_close",
",",
"on_open",
"=",
"self",
".",
"__on_open",
",",
"on_error",
"=",
"self",
".",
"__on_error",
",",
"# We can login using email/pass or API key",
"header",
"=",
"self",
".",
"__get_auth",
"(",
")",
")",
"self",
".",
"wst",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"lambda",
":",
"self",
".",
"ws",
".",
"run_forever",
"(",
")",
")",
"self",
".",
"wst",
".",
"daemon",
"=",
"True",
"self",
".",
"wst",
".",
"start",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Started thread\"",
")",
"# Wait for connect before continuing",
"conn_timeout",
"=",
"5",
"while",
"(",
"not",
"self",
".",
"ws",
".",
"sock",
"or",
"not",
"self",
".",
"ws",
".",
"sock",
".",
"connected",
")",
"and",
"conn_timeout",
"and",
"not",
"self",
".",
"_error",
":",
"sleep",
"(",
"1",
")",
"conn_timeout",
"-=",
"1",
"if",
"not",
"conn_timeout",
"or",
"self",
".",
"_error",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Couldn't connect to WS! Exiting.\"",
")",
"self",
".",
"exit",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L140-L166 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.__get_auth | (self) | Return auth headers. Will use API Keys if present in settings. | Return auth headers. Will use API Keys if present in settings. | [
"Return",
"auth",
"headers",
".",
"Will",
"use",
"API",
"Keys",
"if",
"present",
"in",
"settings",
"."
] | def __get_auth(self):
'''Return auth headers. Will use API Keys if present in settings.'''
if self.shouldAuth is False:
return []
if not settings.API_KEY:
self.logger.info("Authenticating with email/password.")
return [
"email: " + settings.LOGIN,
"password: " + settings.PASSWORD
]
else:
self.logger.info("Authenticating with API Key.")
# To auth to the WS using an API key, we generate a signature of a nonce and
# the WS API endpoint.
nonce = generate_nonce()
return [
"api-nonce: " + str(nonce),
"api-signature: " + generate_signature(settings.API_SECRET, 'GET', '/realtime', nonce, ''),
"api-key:" + settings.API_KEY
] | [
"def",
"__get_auth",
"(",
"self",
")",
":",
"if",
"self",
".",
"shouldAuth",
"is",
"False",
":",
"return",
"[",
"]",
"if",
"not",
"settings",
".",
"API_KEY",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Authenticating with email/password.\"",
")",
"return",
"[",
"\"email: \"",
"+",
"settings",
".",
"LOGIN",
",",
"\"password: \"",
"+",
"settings",
".",
"PASSWORD",
"]",
"else",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Authenticating with API Key.\"",
")",
"# To auth to the WS using an API key, we generate a signature of a nonce and",
"# the WS API endpoint.",
"nonce",
"=",
"generate_nonce",
"(",
")",
"return",
"[",
"\"api-nonce: \"",
"+",
"str",
"(",
"nonce",
")",
",",
"\"api-signature: \"",
"+",
"generate_signature",
"(",
"settings",
".",
"API_SECRET",
",",
"'GET'",
",",
"'/realtime'",
",",
"nonce",
",",
"''",
")",
",",
"\"api-key:\"",
"+",
"settings",
".",
"API_KEY",
"]"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L168-L189 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.__wait_for_account | (self) | On subscribe, this data will come down. Wait for it. | On subscribe, this data will come down. Wait for it. | [
"On",
"subscribe",
"this",
"data",
"will",
"come",
"down",
".",
"Wait",
"for",
"it",
"."
] | def __wait_for_account(self):
'''On subscribe, this data will come down. Wait for it.'''
# Wait for the keys to show up from the ws
while not {'margin', 'position', 'order'} <= set(self.data):
sleep(0.1) | [
"def",
"__wait_for_account",
"(",
"self",
")",
":",
"# Wait for the keys to show up from the ws",
"while",
"not",
"{",
"'margin'",
",",
"'position'",
",",
"'order'",
"}",
"<=",
"set",
"(",
"self",
".",
"data",
")",
":",
"sleep",
"(",
"0.1",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L191-L195 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.__wait_for_symbol | (self, symbol) | On subscribe, this data will come down. Wait for it. | On subscribe, this data will come down. Wait for it. | [
"On",
"subscribe",
"this",
"data",
"will",
"come",
"down",
".",
"Wait",
"for",
"it",
"."
] | def __wait_for_symbol(self, symbol):
'''On subscribe, this data will come down. Wait for it.'''
while not {'instrument', 'trade', 'quote'} <= set(self.data):
sleep(0.1) | [
"def",
"__wait_for_symbol",
"(",
"self",
",",
"symbol",
")",
":",
"while",
"not",
"{",
"'instrument'",
",",
"'trade'",
",",
"'quote'",
"}",
"<=",
"set",
"(",
"self",
".",
"data",
")",
":",
"sleep",
"(",
"0.1",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L197-L200 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.__send_command | (self, command, args=[]) | Send a raw command. | Send a raw command. | [
"Send",
"a",
"raw",
"command",
"."
] | def __send_command(self, command, args=[]):
'''Send a raw command.'''
self.ws.send(json.dumps({"op": command, "args": args})) | [
"def",
"__send_command",
"(",
"self",
",",
"command",
",",
"args",
"=",
"[",
"]",
")",
":",
"self",
".",
"ws",
".",
"send",
"(",
"json",
".",
"dumps",
"(",
"{",
"\"op\"",
":",
"command",
",",
"\"args\"",
":",
"args",
"}",
")",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L202-L204 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/ws/ws_thread.py | python | BitMEXWebsocket.__on_message | (self, ws, message) | Handler for parsing WS messages. | Handler for parsing WS messages. | [
"Handler",
"for",
"parsing",
"WS",
"messages",
"."
] | def __on_message(self, ws, message):
'''Handler for parsing WS messages.'''
message = json.loads(message)
self.logger.debug(json.dumps(message))
table = message['table'] if 'table' in message else None
action = message['action'] if 'action' in message else None
try:
if 'subscribe' in message:
if message['success']:
self.logger.debug("Subscribed to %s." % message['subscribe'])
else:
self.error("Unable to subscribe to %s. Error: \"%s\" Please check and restart." %
(message['request']['args'][0], message['error']))
elif 'status' in message:
if message['status'] == 400:
self.error(message['error'])
if message['status'] == 401:
self.error("API Key incorrect, please check and restart.")
elif action:
if table not in self.data:
self.data[table] = []
if table not in self.keys:
self.keys[table] = []
# There are four possible actions from the WS:
# 'partial' - full table image
# 'insert' - new row
# 'update' - update row
# 'delete' - delete row
if action == 'partial':
self.logger.debug("%s: partial" % table)
self.data[table] += message['data']
# Keys are communicated on partials to let you know how to uniquely identify
# an item. We use it for updates.
self.keys[table] = message['keys']
elif action == 'insert':
self.logger.debug('%s: inserting %s' % (table, message['data']))
self.data[table] += message['data']
# Limit the max length of the table to avoid excessive memory usage.
# Don't trim orders because we'll lose valuable state if we do.
if table != 'order' and len(self.data[table]) > BitMEXWebsocket.MAX_TABLE_LEN:
self.data[table] = self.data[table][(BitMEXWebsocket.MAX_TABLE_LEN // 2):]
elif action == 'update':
self.logger.debug('%s: updating %s' % (table, message['data']))
# Locate the item in the collection and update it.
for updateData in message['data']:
item = findItemByKeys(self.keys[table], self.data[table], updateData)
if not item:
return # No item found to update. Could happen before push
# Log executions
is_canceled = 'ordStatus' in updateData and updateData['ordStatus'] == 'Canceled'
if table == 'order' and 'leavesQty' in updateData and not is_canceled:
instrument = self.get_instrument(item['symbol'])
contExecuted = abs(item['leavesQty'] - updateData['leavesQty'])
self.logger.info("Execution: %s %d Contracts of %s at %.*f" %
(item['side'], contExecuted, item['symbol'],
instrument['tickLog'], item['price']))
item.update(updateData)
# Remove cancelled / filled orders
if table == 'order' and item['leavesQty'] <= 0:
self.data[table].remove(item)
elif action == 'delete':
self.logger.debug('%s: deleting %s' % (table, message['data']))
# Locate the item in the collection and remove it.
for deleteData in message['data']:
item = findItemByKeys(self.keys[table], self.data[table], deleteData)
self.data[table].remove(item)
else:
raise Exception("Unknown action: %s" % action)
except:
self.logger.error(traceback.format_exc()) | [
"def",
"__on_message",
"(",
"self",
",",
"ws",
",",
"message",
")",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"json",
".",
"dumps",
"(",
"message",
")",
")",
"table",
"=",
"message",
"[",
"'table'",
"]",
"if",
"'table'",
"in",
"message",
"else",
"None",
"action",
"=",
"message",
"[",
"'action'",
"]",
"if",
"'action'",
"in",
"message",
"else",
"None",
"try",
":",
"if",
"'subscribe'",
"in",
"message",
":",
"if",
"message",
"[",
"'success'",
"]",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Subscribed to %s.\"",
"%",
"message",
"[",
"'subscribe'",
"]",
")",
"else",
":",
"self",
".",
"error",
"(",
"\"Unable to subscribe to %s. Error: \\\"%s\\\" Please check and restart.\"",
"%",
"(",
"message",
"[",
"'request'",
"]",
"[",
"'args'",
"]",
"[",
"0",
"]",
",",
"message",
"[",
"'error'",
"]",
")",
")",
"elif",
"'status'",
"in",
"message",
":",
"if",
"message",
"[",
"'status'",
"]",
"==",
"400",
":",
"self",
".",
"error",
"(",
"message",
"[",
"'error'",
"]",
")",
"if",
"message",
"[",
"'status'",
"]",
"==",
"401",
":",
"self",
".",
"error",
"(",
"\"API Key incorrect, please check and restart.\"",
")",
"elif",
"action",
":",
"if",
"table",
"not",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
"[",
"table",
"]",
"=",
"[",
"]",
"if",
"table",
"not",
"in",
"self",
".",
"keys",
":",
"self",
".",
"keys",
"[",
"table",
"]",
"=",
"[",
"]",
"# There are four possible actions from the WS:",
"# 'partial' - full table image",
"# 'insert' - new row",
"# 'update' - update row",
"# 'delete' - delete row",
"if",
"action",
"==",
"'partial'",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"%s: partial\"",
"%",
"table",
")",
"self",
".",
"data",
"[",
"table",
"]",
"+=",
"message",
"[",
"'data'",
"]",
"# Keys are communicated on partials to let you know how to uniquely identify",
"# an item. We use it for updates.",
"self",
".",
"keys",
"[",
"table",
"]",
"=",
"message",
"[",
"'keys'",
"]",
"elif",
"action",
"==",
"'insert'",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s: inserting %s'",
"%",
"(",
"table",
",",
"message",
"[",
"'data'",
"]",
")",
")",
"self",
".",
"data",
"[",
"table",
"]",
"+=",
"message",
"[",
"'data'",
"]",
"# Limit the max length of the table to avoid excessive memory usage.",
"# Don't trim orders because we'll lose valuable state if we do.",
"if",
"table",
"!=",
"'order'",
"and",
"len",
"(",
"self",
".",
"data",
"[",
"table",
"]",
")",
">",
"BitMEXWebsocket",
".",
"MAX_TABLE_LEN",
":",
"self",
".",
"data",
"[",
"table",
"]",
"=",
"self",
".",
"data",
"[",
"table",
"]",
"[",
"(",
"BitMEXWebsocket",
".",
"MAX_TABLE_LEN",
"//",
"2",
")",
":",
"]",
"elif",
"action",
"==",
"'update'",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s: updating %s'",
"%",
"(",
"table",
",",
"message",
"[",
"'data'",
"]",
")",
")",
"# Locate the item in the collection and update it.",
"for",
"updateData",
"in",
"message",
"[",
"'data'",
"]",
":",
"item",
"=",
"findItemByKeys",
"(",
"self",
".",
"keys",
"[",
"table",
"]",
",",
"self",
".",
"data",
"[",
"table",
"]",
",",
"updateData",
")",
"if",
"not",
"item",
":",
"return",
"# No item found to update. Could happen before push",
"# Log executions",
"is_canceled",
"=",
"'ordStatus'",
"in",
"updateData",
"and",
"updateData",
"[",
"'ordStatus'",
"]",
"==",
"'Canceled'",
"if",
"table",
"==",
"'order'",
"and",
"'leavesQty'",
"in",
"updateData",
"and",
"not",
"is_canceled",
":",
"instrument",
"=",
"self",
".",
"get_instrument",
"(",
"item",
"[",
"'symbol'",
"]",
")",
"contExecuted",
"=",
"abs",
"(",
"item",
"[",
"'leavesQty'",
"]",
"-",
"updateData",
"[",
"'leavesQty'",
"]",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Execution: %s %d Contracts of %s at %.*f\"",
"%",
"(",
"item",
"[",
"'side'",
"]",
",",
"contExecuted",
",",
"item",
"[",
"'symbol'",
"]",
",",
"instrument",
"[",
"'tickLog'",
"]",
",",
"item",
"[",
"'price'",
"]",
")",
")",
"item",
".",
"update",
"(",
"updateData",
")",
"# Remove cancelled / filled orders",
"if",
"table",
"==",
"'order'",
"and",
"item",
"[",
"'leavesQty'",
"]",
"<=",
"0",
":",
"self",
".",
"data",
"[",
"table",
"]",
".",
"remove",
"(",
"item",
")",
"elif",
"action",
"==",
"'delete'",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s: deleting %s'",
"%",
"(",
"table",
",",
"message",
"[",
"'data'",
"]",
")",
")",
"# Locate the item in the collection and remove it.",
"for",
"deleteData",
"in",
"message",
"[",
"'data'",
"]",
":",
"item",
"=",
"findItemByKeys",
"(",
"self",
".",
"keys",
"[",
"table",
"]",
",",
"self",
".",
"data",
"[",
"table",
"]",
",",
"deleteData",
")",
"self",
".",
"data",
"[",
"table",
"]",
".",
"remove",
"(",
"item",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unknown action: %s\"",
"%",
"action",
")",
"except",
":",
"self",
".",
"logger",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/ws/ws_thread.py#L206-L283 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/APIKeyAuth.py | python | generate_signature | (secret, verb, url, nonce, data) | return signature | Generate a request signature compatible with BitMEX. | Generate a request signature compatible with BitMEX. | [
"Generate",
"a",
"request",
"signature",
"compatible",
"with",
"BitMEX",
"."
] | def generate_signature(secret, verb, url, nonce, data):
"""Generate a request signature compatible with BitMEX."""
# Parse the url so we can remove the base and extract just the path.
parsedURL = urlparse(url)
path = parsedURL.path
if parsedURL.query:
path = path + '?' + parsedURL.query
# print "Computing HMAC: %s" % verb + path + str(nonce) + data
message = verb + path + str(nonce) + data
signature = hmac.new(bytes(secret, 'utf8'), bytes(message, 'utf8'), digestmod=hashlib.sha256).hexdigest()
return signature | [
"def",
"generate_signature",
"(",
"secret",
",",
"verb",
",",
"url",
",",
"nonce",
",",
"data",
")",
":",
"# Parse the url so we can remove the base and extract just the path.",
"parsedURL",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"parsedURL",
".",
"path",
"if",
"parsedURL",
".",
"query",
":",
"path",
"=",
"path",
"+",
"'?'",
"+",
"parsedURL",
".",
"query",
"# print \"Computing HMAC: %s\" % verb + path + str(nonce) + data",
"message",
"=",
"verb",
"+",
"path",
"+",
"str",
"(",
"nonce",
")",
"+",
"data",
"signature",
"=",
"hmac",
".",
"new",
"(",
"bytes",
"(",
"secret",
",",
"'utf8'",
")",
",",
"bytes",
"(",
"message",
",",
"'utf8'",
")",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
".",
"hexdigest",
"(",
")",
"return",
"signature"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/APIKeyAuth.py#L47-L59 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/APIKeyAuth.py | python | APIKeyAuth.__init__ | (self, apiKey, apiSecret) | Init with Key & Secret. | Init with Key & Secret. | [
"Init",
"with",
"Key",
"&",
"Secret",
"."
] | def __init__(self, apiKey, apiSecret):
"""Init with Key & Secret."""
self.apiKey = apiKey
self.apiSecret = apiSecret | [
"def",
"__init__",
"(",
"self",
",",
"apiKey",
",",
"apiSecret",
")",
":",
"self",
".",
"apiKey",
"=",
"apiKey",
"self",
".",
"apiSecret",
"=",
"apiSecret"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/APIKeyAuth.py#L15-L18 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/APIKeyAuth.py | python | APIKeyAuth.__call__ | (self, r) | return r | Called when forming a request - generates api key headers. | Called when forming a request - generates api key headers. | [
"Called",
"when",
"forming",
"a",
"request",
"-",
"generates",
"api",
"key",
"headers",
"."
] | def __call__(self, r):
"""Called when forming a request - generates api key headers."""
# modify and return the request
nonce = generate_nonce()
r.headers['api-nonce'] = str(nonce)
r.headers['api-key'] = self.apiKey
r.headers['api-signature'] = generate_signature(self.apiSecret, r.method, r.url, nonce, r.body or '')
return r | [
"def",
"__call__",
"(",
"self",
",",
"r",
")",
":",
"# modify and return the request",
"nonce",
"=",
"generate_nonce",
"(",
")",
"r",
".",
"headers",
"[",
"'api-nonce'",
"]",
"=",
"str",
"(",
"nonce",
")",
"r",
".",
"headers",
"[",
"'api-key'",
"]",
"=",
"self",
".",
"apiKey",
"r",
".",
"headers",
"[",
"'api-signature'",
"]",
"=",
"generate_signature",
"(",
"self",
".",
"apiSecret",
",",
"r",
".",
"method",
",",
"r",
".",
"url",
",",
"nonce",
",",
"r",
".",
"body",
"or",
"''",
")",
"return",
"r"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/APIKeyAuth.py#L20-L28 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/APIKeyAuthWithExpires.py | python | APIKeyAuthWithExpires.__init__ | (self, apiKey, apiSecret) | Init with Key & Secret. | Init with Key & Secret. | [
"Init",
"with",
"Key",
"&",
"Secret",
"."
] | def __init__(self, apiKey, apiSecret):
"""Init with Key & Secret."""
self.apiKey = apiKey
self.apiSecret = apiSecret | [
"def",
"__init__",
"(",
"self",
",",
"apiKey",
",",
"apiSecret",
")",
":",
"self",
".",
"apiKey",
"=",
"apiKey",
"self",
".",
"apiSecret",
"=",
"apiSecret"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/APIKeyAuthWithExpires.py#L15-L18 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/APIKeyAuthWithExpires.py | python | APIKeyAuthWithExpires.__call__ | (self, r) | return r | Called when forming a request - generates api key headers. This call uses `expires` instead of nonce.
This way it will not collide with other processes using the same API Key if requests arrive out of order.
For more details, see https://www.bitmex.com/app/apiKeys | Called when forming a request - generates api key headers. This call uses `expires` instead of nonce. | [
"Called",
"when",
"forming",
"a",
"request",
"-",
"generates",
"api",
"key",
"headers",
".",
"This",
"call",
"uses",
"expires",
"instead",
"of",
"nonce",
"."
] | def __call__(self, r):
"""
Called when forming a request - generates api key headers. This call uses `expires` instead of nonce.
This way it will not collide with other processes using the same API Key if requests arrive out of order.
For more details, see https://www.bitmex.com/app/apiKeys
"""
# modify and return the request
expires = int(round(time.time()) + 5) # 5s grace period in case of clock skew
r.headers['api-expires'] = str(expires)
r.headers['api-key'] = self.apiKey
r.headers['api-signature'] = self.generate_signature(self.apiSecret, r.method, r.url, expires, r.body or '')
return r | [
"def",
"__call__",
"(",
"self",
",",
"r",
")",
":",
"# modify and return the request",
"expires",
"=",
"int",
"(",
"round",
"(",
"time",
".",
"time",
"(",
")",
")",
"+",
"5",
")",
"# 5s grace period in case of clock skew",
"r",
".",
"headers",
"[",
"'api-expires'",
"]",
"=",
"str",
"(",
"expires",
")",
"r",
".",
"headers",
"[",
"'api-key'",
"]",
"=",
"self",
".",
"apiKey",
"r",
".",
"headers",
"[",
"'api-signature'",
"]",
"=",
"self",
".",
"generate_signature",
"(",
"self",
".",
"apiSecret",
",",
"r",
".",
"method",
",",
"r",
".",
"url",
",",
"expires",
",",
"r",
".",
"body",
"or",
"''",
")",
"return",
"r"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/APIKeyAuthWithExpires.py#L20-L33 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/APIKeyAuthWithExpires.py | python | APIKeyAuthWithExpires.generate_signature | (self, secret, verb, url, nonce, data) | return signature | Generate a request signature compatible with BitMEX. | Generate a request signature compatible with BitMEX. | [
"Generate",
"a",
"request",
"signature",
"compatible",
"with",
"BitMEX",
"."
] | def generate_signature(self, secret, verb, url, nonce, data):
"""Generate a request signature compatible with BitMEX."""
# Parse the url so we can remove the base and extract just the path.
parsedURL = urlparse(url)
path = parsedURL.path
if parsedURL.query:
path = path + '?' + parsedURL.query
# print "Computing HMAC: %s" % verb + path + str(nonce) + data
message = verb + path + str(nonce) + data
signature = hmac.new(bytes(secret, 'utf8'), bytes(message, 'utf8'), digestmod=hashlib.sha256).hexdigest()
return signature | [
"def",
"generate_signature",
"(",
"self",
",",
"secret",
",",
"verb",
",",
"url",
",",
"nonce",
",",
"data",
")",
":",
"# Parse the url so we can remove the base and extract just the path.",
"parsedURL",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"parsedURL",
".",
"path",
"if",
"parsedURL",
".",
"query",
":",
"path",
"=",
"path",
"+",
"'?'",
"+",
"parsedURL",
".",
"query",
"# print \"Computing HMAC: %s\" % verb + path + str(nonce) + data",
"message",
"=",
"verb",
"+",
"path",
"+",
"str",
"(",
"nonce",
")",
"+",
"data",
"signature",
"=",
"hmac",
".",
"new",
"(",
"bytes",
"(",
"secret",
",",
"'utf8'",
")",
",",
"bytes",
"(",
"message",
",",
"'utf8'",
")",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
".",
"hexdigest",
"(",
")",
"return",
"signature"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/APIKeyAuthWithExpires.py#L48-L60 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/AccessTokenAuth.py | python | AccessTokenAuth.__init__ | (self, accessToken) | Init with Token. | Init with Token. | [
"Init",
"with",
"Token",
"."
] | def __init__(self, accessToken):
"""Init with Token."""
self.token = accessToken | [
"def",
"__init__",
"(",
"self",
",",
"accessToken",
")",
":",
"self",
".",
"token",
"=",
"accessToken"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/AccessTokenAuth.py#L8-L10 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | market_maker/auth/AccessTokenAuth.py | python | AccessTokenAuth.__call__ | (self, r) | return r | Called when forming a request - generates access token header. | Called when forming a request - generates access token header. | [
"Called",
"when",
"forming",
"a",
"request",
"-",
"generates",
"access",
"token",
"header",
"."
] | def __call__(self, r):
"""Called when forming a request - generates access token header."""
if (self.token):
r.headers['access-token'] = self.token
return r | [
"def",
"__call__",
"(",
"self",
",",
"r",
")",
":",
"if",
"(",
"self",
".",
"token",
")",
":",
"r",
".",
"headers",
"[",
"'access-token'",
"]",
"=",
"self",
".",
"token",
"return",
"r"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/market_maker/auth/AccessTokenAuth.py#L12-L16 |
|
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | util/generate-api-key.py | python | BitMEX.create_key | (self) | Create an API key. | Create an API key. | [
"Create",
"an",
"API",
"key",
"."
] | def create_key(self):
"""Create an API key."""
print("Creating key. Please input the following options:")
name = input("Key name (optional): ")
print("To make this key more secure, you should restrict the IP addresses that can use it. ")
print("To use with all IPs, leave blank or use 0.0.0.0/0.")
print("To use with a single IP, append '/32', such as 207.39.29.22/32. ")
print("See this reference on CIDR blocks: http://software77.net/cidr-101.html")
cidr = input("CIDR (optional): ")
# Set up permissions
permissions = []
if strtobool(input("Should this key be able to submit orders? [y/N] ") or 'N'):
permissions.append('order')
if strtobool(input("Should this key be able to submit withdrawals? [y/N] ") or 'N'):
permissions.append('withdraw')
otpToken = input("OTP Token (If enabled. If not, press <enter>): ")
key = self._curl_bitmex("/apiKey",
postdict={"name": name, "cidr": cidr, "enabled": True, "token": otpToken,
"permissions": string.join(permissions, ',')})
print("Key created. Details:\n")
print("API Key: " + key["id"])
print("Secret: " + key["secret"])
print("\nSafeguard your secret key! If somebody gets a hold of your API key and secret,")
print("your account can be taken over completely.")
print("\nKey generation complete.") | [
"def",
"create_key",
"(",
"self",
")",
":",
"print",
"(",
"\"Creating key. Please input the following options:\"",
")",
"name",
"=",
"input",
"(",
"\"Key name (optional): \"",
")",
"print",
"(",
"\"To make this key more secure, you should restrict the IP addresses that can use it. \"",
")",
"print",
"(",
"\"To use with all IPs, leave blank or use 0.0.0.0/0.\"",
")",
"print",
"(",
"\"To use with a single IP, append '/32', such as 207.39.29.22/32. \"",
")",
"print",
"(",
"\"See this reference on CIDR blocks: http://software77.net/cidr-101.html\"",
")",
"cidr",
"=",
"input",
"(",
"\"CIDR (optional): \"",
")",
"# Set up permissions",
"permissions",
"=",
"[",
"]",
"if",
"strtobool",
"(",
"input",
"(",
"\"Should this key be able to submit orders? [y/N] \"",
")",
"or",
"'N'",
")",
":",
"permissions",
".",
"append",
"(",
"'order'",
")",
"if",
"strtobool",
"(",
"input",
"(",
"\"Should this key be able to submit withdrawals? [y/N] \"",
")",
"or",
"'N'",
")",
":",
"permissions",
".",
"append",
"(",
"'withdraw'",
")",
"otpToken",
"=",
"input",
"(",
"\"OTP Token (If enabled. If not, press <enter>): \"",
")",
"key",
"=",
"self",
".",
"_curl_bitmex",
"(",
"\"/apiKey\"",
",",
"postdict",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"cidr\"",
":",
"cidr",
",",
"\"enabled\"",
":",
"True",
",",
"\"token\"",
":",
"otpToken",
",",
"\"permissions\"",
":",
"string",
".",
"join",
"(",
"permissions",
",",
"','",
")",
"}",
")",
"print",
"(",
"\"Key created. Details:\\n\"",
")",
"print",
"(",
"\"API Key: \"",
"+",
"key",
"[",
"\"id\"",
"]",
")",
"print",
"(",
"\"Secret: \"",
"+",
"key",
"[",
"\"secret\"",
"]",
")",
"print",
"(",
"\"\\nSafeguard your secret key! If somebody gets a hold of your API key and secret,\"",
")",
"print",
"(",
"\"your account can be taken over completely.\"",
")",
"print",
"(",
"\"\\nKey generation complete.\"",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/util/generate-api-key.py#L79-L107 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | util/generate-api-key.py | python | BitMEX.list_keys | (self) | List your API Keys. | List your API Keys. | [
"List",
"your",
"API",
"Keys",
"."
] | def list_keys(self):
"""List your API Keys."""
keys = self._curl_bitmex("/apiKey/")
print(json.dumps(keys, sort_keys=True, indent=4)) | [
"def",
"list_keys",
"(",
"self",
")",
":",
"keys",
"=",
"self",
".",
"_curl_bitmex",
"(",
"\"/apiKey/\"",
")",
"print",
"(",
"json",
".",
"dumps",
"(",
"keys",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/util/generate-api-key.py#L109-L112 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | util/generate-api-key.py | python | BitMEX.enable_key | (self) | Enable an existing API Key. | Enable an existing API Key. | [
"Enable",
"an",
"existing",
"API",
"Key",
"."
] | def enable_key(self):
"""Enable an existing API Key."""
print("This command will enable a disabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_bitmex("/apiKey/enable",
postdict={"apiKeyID": apiKeyID})
print("Key with ID %s enabled." % key["id"])
except:
print("Unable to enable key, please try again.")
self.enable_key() | [
"def",
"enable_key",
"(",
"self",
")",
":",
"print",
"(",
"\"This command will enable a disabled key.\"",
")",
"apiKeyID",
"=",
"input",
"(",
"\"API Key ID: \"",
")",
"try",
":",
"key",
"=",
"self",
".",
"_curl_bitmex",
"(",
"\"/apiKey/enable\"",
",",
"postdict",
"=",
"{",
"\"apiKeyID\"",
":",
"apiKeyID",
"}",
")",
"print",
"(",
"\"Key with ID %s enabled.\"",
"%",
"key",
"[",
"\"id\"",
"]",
")",
"except",
":",
"print",
"(",
"\"Unable to enable key, please try again.\"",
")",
"self",
".",
"enable_key",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/util/generate-api-key.py#L114-L124 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | util/generate-api-key.py | python | BitMEX.disable_key | (self) | Disable an existing API Key. | Disable an existing API Key. | [
"Disable",
"an",
"existing",
"API",
"Key",
"."
] | def disable_key(self):
"""Disable an existing API Key."""
print("This command will disable a enabled key.")
apiKeyID = input("API Key ID: ")
try:
key = self._curl_bitmex("/apiKey/disable",
postdict={"apiKeyID": apiKeyID})
print("Key with ID %s disabled." % key["id"])
except:
print("Unable to disable key, please try again.")
self.disable_key() | [
"def",
"disable_key",
"(",
"self",
")",
":",
"print",
"(",
"\"This command will disable a enabled key.\"",
")",
"apiKeyID",
"=",
"input",
"(",
"\"API Key ID: \"",
")",
"try",
":",
"key",
"=",
"self",
".",
"_curl_bitmex",
"(",
"\"/apiKey/disable\"",
",",
"postdict",
"=",
"{",
"\"apiKeyID\"",
":",
"apiKeyID",
"}",
")",
"print",
"(",
"\"Key with ID %s disabled.\"",
"%",
"key",
"[",
"\"id\"",
"]",
")",
"except",
":",
"print",
"(",
"\"Unable to disable key, please try again.\"",
")",
"self",
".",
"disable_key",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/util/generate-api-key.py#L126-L136 |
||
Behappy123/market-maker | aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4 | util/generate-api-key.py | python | BitMEX.delete_key | (self) | Delete an existing API Key. | Delete an existing API Key. | [
"Delete",
"an",
"existing",
"API",
"Key",
"."
] | def delete_key(self):
"""Delete an existing API Key."""
print("This command will delete an API key.")
apiKeyID = input("API Key ID: ")
try:
self._curl_bitmex("/apiKey/",
postdict={"apiKeyID": apiKeyID}, verb='DELETE')
print("Key with ID %s deleted." % apiKeyID)
except:
print("Unable to delete key, please try again.")
self.delete_key() | [
"def",
"delete_key",
"(",
"self",
")",
":",
"print",
"(",
"\"This command will delete an API key.\"",
")",
"apiKeyID",
"=",
"input",
"(",
"\"API Key ID: \"",
")",
"try",
":",
"self",
".",
"_curl_bitmex",
"(",
"\"/apiKey/\"",
",",
"postdict",
"=",
"{",
"\"apiKeyID\"",
":",
"apiKeyID",
"}",
",",
"verb",
"=",
"'DELETE'",
")",
"print",
"(",
"\"Key with ID %s deleted.\"",
"%",
"apiKeyID",
")",
"except",
":",
"print",
"(",
"\"Unable to delete key, please try again.\"",
")",
"self",
".",
"delete_key",
"(",
")"
] | https://github.com/Behappy123/market-maker/blob/aaed8cf8c994771e0a6ff070ce19b15efbfbd1c4/util/generate-api-key.py#L138-L148 |
||
Billwilliams1952/PiCameraApp | 61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0 | Source/BasicControls.py | python | BasicControls.BuildPage | ( self ) | Add additional controls if JPG is selected
Certain file formats accept additional options which can be specified as keyword
arguments. Currently, only the 'jpeg' encoder accepts additional options, which are:
quality - Defines the quality of the JPEG encoder as an integer ranging from 1 to 100.
Defaults to 85. Please note that JPEG quality is not a percentage and
definitions of quality vary widely.
restart - Defines the restart interval for the JPEG encoder as a number of JPEG MCUs.
The actual restart interval used will be a multiple of the number of MCUs per row in the resulting image.
thumbnail - Defines the size and quality of the thumbnail to embed in the Exif
metadata. Specifying None disables thumbnail generation. Otherwise,
specify a tuple of (width, height, quality). Defaults to (64, 48, 35).
bayer - If True, the raw bayer data from the camera’s sensor is included in the
Exif metadata. | Add additional controls if JPG is selected
Certain file formats accept additional options which can be specified as keyword
arguments. Currently, only the 'jpeg' encoder accepts additional options, which are: | [
"Add",
"additional",
"controls",
"if",
"JPG",
"is",
"selected",
"Certain",
"file",
"formats",
"accept",
"additional",
"options",
"which",
"can",
"be",
"specified",
"as",
"keyword",
"arguments",
".",
"Currently",
"only",
"the",
"jpeg",
"encoder",
"accepts",
"additional",
"options",
"which",
"are",
":"
] | def BuildPage ( self ):
#### TODO: Add Rotation. Cleanup and organize controls
# Add handling of Image Effect Params
#----------- Select port for image captures ------------
f1 = MyLabelFrame(self,'Select port for image captures',0,0,span=2)
self.UseVidPort = MyBooleanVar(False)
self.UseRadio = MyRadio(f1,'Use Still Port',False,self.UseVidPort,
self.UseVideoPort,0,0,'W',tip=100)
MyRadio(f1,'Use Video Port',True,self.UseVidPort,
self.UseVideoPort,0,1,'W',tip=101)
f2 = ttk.Frame(f1) # Sub frame
f2.grid(row=1,column=0,columnspan=4,sticky='NSEW')
self.VideoDenoise = MyBooleanVar(True)
b = ttk.Checkbutton(f2,text='Video denoise',variable=self.VideoDenoise,
command=self.VideoDenoiseChecked)
b.grid(row=1,column=0,sticky='NW',padx=5)
ToolTip(b,msg=103)
self.VideoStab = MyBooleanVar(False)
b = ttk.Checkbutton(f2,text='Video stabilization',variable=self.VideoStab,
command=self.VideoStabChecked)
b.grid(row=1,column=1,sticky='NW')
ToolTip(b, msg=105)
self.ImageDenoise = MyBooleanVar(True)
b = ttk.Checkbutton(f2,text='Image denoise',variable=self.ImageDenoise,
command=self.ImageDenoiseChecked)
b.grid(row=1,column=2,sticky='NW',padx=10)
ToolTip(b, msg=104)
#--------------- Picture/Video Capture Size ---------------
f = MyLabelFrame(self,'Picture/Video capture size in pixels',1,0)
#f.columnconfigure(0,weight=1)
f1 = ttk.Frame(f) # Sub frames to frame f
f1.grid(row=1,column=0,sticky='NSEW')
f1.columnconfigure(1,weight=1)
self.UseFixedResolutions = BooleanVar()
self.UseFixedResolutions.set(True)
self.UseFixedResRadio = ttk.Radiobutton(f1,text='Use fixed:',
variable=self.UseFixedResolutions,
value=True,command=self.UseFixedResRadios,padding=(5,5,5,5))
ToolTip(self.UseFixedResRadio,120)
self.UseFixedResRadio.grid(row=0,column=0,sticky='NW')
self.FixedResolutionsCombo = Combobox(f1,state='readonly',width=25)
self.FixedResolutionsCombo.bind('<<ComboboxSelected>>',
self.FixedResolutionChanged)
self.FixedResolutionsCombo.grid(row=0,column=1,columnspan=3,sticky='W')
ToolTip(self.FixedResolutionsCombo,121)
#------------ Capture Width and Height ----------------
# OrderedDict is used to ensure the keys stay in the same order as
# entered. I want the combobox to display in this order
#### TODO: Must check resolution and framerate and disable the Video
# button if we exceed limits of the modes
# Framerate 1-30 fps up to 1920x1080 16:9 aspect ratio
# Framerate 1-15 fps up to 2592 x 1944 4:3 aspect ratio
# Framerate 0.1666 to 1 fps up to 2592 x 1944 4:3 aspect ratio
# Framerate 1-42 fps up t0 1296 x 972 4:3 aspect ratio
# Framerate 1-49 fps up to 1296 x 730 16:9 aspect ratio
# Framerate 42.1 - 60 fps to 640 x 480 4:3 aspect ratio
# Framerate 60.1 - 90 fps to 640 x 480 4:3 aspect ratio
self.StandardResolutions = OrderedDict([ \
('CGA', (320,200)), ('QVGA', (320,240)),
('VGA', (640,480)), ('PAL', (768,576)),
('480p', (720,480)), ('576p', (720,576)),
('WVGA', (800,480)), ('SVGA', (800,600)),
('FWVGA', (854,480)), ('WSVGA', (1024,600)),
('XGA', (1024,768)), ('HD 720', (1280,720)),
('WXGA_1', (1280,768)), ('WXGA_2', (1280,800)),
('SXGA', (1280,1024)), ('SXGA+', (1400,1050)),
('UXGA', (1600,1200)), ('WSXGA+', (1680,1050)),
('HD 1080', (1920,1080)), ('WUXGA', (1920,1200)),
('2K', (2048,1080)), ('QXGA', (2048, 1536)),
('WQXGA', (2560,1600)), ('MAX Resolution', (2592,1944)),
])
vals = []
for key in self.StandardResolutions.keys():
vals.append('%s: (%dx%d)' % (key, # Tabs not working?!!
self.StandardResolutions[key][0],
self.StandardResolutions[key][1]))
self.FixedResolutionsCombo['values'] = vals
self.FixedResolutionsCombo.current(10)
f2 = ttk.Frame(f) # subframe to frame f
f2.grid(row=2,column=0,sticky='NSEW')
f2.columnconfigure(2,weight=1)
f2.columnconfigure(4,weight=1)
b2 = ttk.Radiobutton(f2,text='Roll your own:',
variable=self.UseFixedResolutions,
value=False,command=self.UseFixedResRadios,padding=(5,5,5,5))
b2.grid(row=1,column=0,sticky='NW')
ToolTip(b2,122)
Label(f2,text="Width:",anchor=E).grid(column=1,row=1,sticky='E',ipadx=3,ipady=3)
Widths = []
for i in range(1,82):
Widths.append(32 * i) # Widths can be in 32 byte increments
self.cb = MyComboBox ( f2, Widths, current=10,
callback=self.ResolutionChanged, width=5, row=1, col=2,
sticky='W', state='disabled', tip=123)
Label(f2,text="Height:",anchor=E).grid(column=3,row=1,sticky='W',ipadx=5,ipady=3)
Heights = []
for i in range(1,123):
Heights.append(16 * i) # heights in 16 byte increments
self.cb1 = MyComboBox ( f2, Heights, current=10,
callback=self.ResolutionChanged, width=5, row=1, col=4,
sticky='W', state='disabled', tip=124)
ttk.Label(f2,text='Actual:').grid(row=2,column=1,sticky='E')
self.WidthLabel = ttk.Label(f2,style='DataLabel.TLabel')
self.WidthLabel.grid(row=2,column=2,sticky='W')
ToolTip(self.WidthLabel,125)
ttk.Label(f2,text='Actual:').grid(row=2,column=3,sticky='E')
self.HeightLabel = ttk.Label(f2,style='DataLabel.TLabel')
self.HeightLabel.grid(row=2,column=4,sticky='W')
ToolTip(self.HeightLabel,126)
Separator(f,orient=HORIZONTAL).grid(pady=5,row=3,column=0,
columnspan=4,sticky='EW')
#--------------- Zoom Region Before ----------------
f4 = MyLabelFrame(f,'Zoom region of interest before taking '+
'picture/video',4,0)
#f4.columnconfigure(1,weight=1)
#f4.columnconfigure(3,weight=1)
Label(f4,text='X:').grid(row=0,column=0,sticky='E')
self.Xzoom = ttk.Scale(f4,from_=0.0,to=0.94,orient='horizontal')
self.Xzoom.grid(row=0,column=1,sticky='W',padx=5,pady=3)
self.Xzoom.set(0.0)
ToolTip(self.Xzoom,130)
Label(f4,text='Y:').grid(row=0,column=2,sticky='E')
self.Yzoom = ttk.Scale(f4,from_=0.0,to=0.94,orient='horizontal')
self.Yzoom.grid(row=0,column=3,sticky='W',padx=5,pady=3)
self.Yzoom.set(0.0)
ToolTip(self.Yzoom,131)
Label(f4,text='Width:').grid(row=1,column=0,sticky='E')
self.Widthzoom = ttk.Scale(f4,from_=0.05,to=1.0,orient='horizontal')
self.Widthzoom.grid(row=1,column=1,sticky='W',padx=5,pady=3)
self.Widthzoom.set(1.0)
ToolTip(self.Widthzoom,132)
Label(f4,text='Height:').grid(row=1,column=2,sticky='E')
self.Heightzoom = ttk.Scale(f4,from_=0.05,to=1.0,orient='horizontal')
self.Heightzoom.grid(row=1,column=3,sticky='W',padx=5,pady=3)
self.Heightzoom.set(1.0)
ToolTip(self.Heightzoom,133)
# WLW THIS IS A PROBLEM
image = PIL.Image.open('Assets/reset.png') #.resize((16,16))
self.resetImage = GetPhotoImage(image.resize((16,16)))
self.ResetZoomButton = ttk.Button(f4,image=self.resetImage,
command=self.ZoomReset)
self.ResetZoomButton.grid(row=0,column=4,rowspan=2,sticky='W')
ToolTip(self.ResetZoomButton,134)
self.Xzoom.config(command=lambda newval,
widget=self.Xzoom:self.Zoom(newval,widget))
self.Yzoom.config(command=lambda newval,
widget=self.Yzoom:self.Zoom(newval,widget))
self.Widthzoom.config(command=lambda newval,
widget=self.Widthzoom:self.Zoom(newval,widget))
self.Heightzoom.config(command=lambda newval,
widget=self.Heightzoom:self.Zoom(newval,widget))
Separator(f,orient=HORIZONTAL).grid(pady=5,row=5,column=0,
columnspan=3,sticky='EW')
#--------------- Resize Image After ----------------
f4 = MyLabelFrame(f,'Resize image after taking picture/video',6,0)
#f4.columnconfigure(3,weight=1)
#f4.columnconfigure(5,weight=1)
b = MyBooleanVar(False)
self.ResizeAfterNone = MyRadio(f4,'None (Default)',False,b,
self.AllowImageResizeAfter,0,0,'W',pad=(0,5,0,5), tip=140)
MyRadio(f4,'Resize',True,b,self.AllowImageResizeAfter,
0,1,'W',pad=(5,5,0,5),tip=141)
Label(f4,text="Width:",anchor=E).grid(column=2,row=0,sticky='E',ipadx=3,ipady=3)
self.resizeWidthAfterCombo = MyComboBox ( f4, Widths, current=10,
callback=self.ResizeAfterChanged, width=5, row=0, col=3,
sticky='W', state='disabled', tip=142)
Label(f4,text="Height:",anchor=E).grid(column=4,row=0,sticky='W',ipadx=5,ipady=3)
self.resizeHeightAfterCombo = MyComboBox ( f4, Heights, current=10,
callback=self.ResizeAfterChanged, width=5, row=0, col=5,
sticky='W', state='disabled', tip=143)
self.resizeAfter = None
#--------------- Quick Adjustments ----------------
f = MyLabelFrame(self,'Quick adjustments',2,0)
#f.columnconfigure(2,weight=1)
#-Brightness
self.brightLabel, self.brightness, val = \
self.SetupLabelCombo(f,'Brightness:',0,0,0, 100,
self.CameraBrightnessChanged, self.camera.brightness )
self.CameraBrightnessChanged(val)
ToolTip(self.brightness,msg=150)
#-Contrast
self.contrastLabel, self.contrast, val = \
self.SetupLabelCombo(f,'Contrast:',0,3,-100, 100,
self.ContrastChanged, self.camera.contrast )
self.ContrastChanged(val)
ToolTip(self.contrast,msg=151)
#-Saturation
self.saturationLabel, self.saturation, val = \
self.SetupLabelCombo(f,'Saturation:',1,0,-100, 100,
self.SaturationChanged, self.camera.saturation, label='Sat' )
self.SaturationChanged(val)
ToolTip(self.saturation,msg=152)
#-Sharpness
self.sharpnessLabel, self.sharpness, val = \
self.SetupLabelCombo(f,'Sharpness:',1,3,-100, 100,
self.SharpnessChanged, self.camera.sharpness )
self.SharpnessChanged(val)
ToolTip(self.sharpness,msg=153)
#-Reset
#self.ResetGeneralButton = Button(f,image=self.resetImage,width=5,
#command=self.ResetGeneralSliders)
#self.ResetGeneralButton.grid(row=4,column=2,sticky='W',padx=5)
#ToolTip(self.ResetGeneralButton,msg=154)
#--------------- Image Effects ----------------
f = MyLabelFrame(self,'Preprogrammed image effects',3,0)
#f.columnconfigure(2,weight=1)
v = MyBooleanVar(False)
self.NoEffectsRadio = MyRadio(f,'None (Default)',False,v,
self.EffectsChecked,0,0,'W',tip=160)
MyRadio(f,'Select effect:',True,v,self.EffectsChecked,0,1,'W',
tip=161)
self.effects = Combobox(f,height=15,width=10,state='readonly')#,width=15)
self.effects.grid(row=0,column=2,sticky='W')
effects = list(self.camera.IMAGE_EFFECTS.keys()) # python 3 workaround
effects.remove('none')
effects.sort() #cmp=lambda x,y: cmp(x.lower(),y.lower())) # not python 3
self.effects['values'] = effects
self.effects.current(0)
self.effects.bind('<<ComboboxSelected>>',self.EffectsChanged)
ToolTip(self.effects, msg=162)
self.ModParams = ttk.Button(f,text='Params...',
command=self.ModifyEffectsParamsPressed,underline=0,padding=(5,3,5,3),width=8)
self.ModParams.grid(row=0,column=3,sticky=EW,padx=5)
ToolTip(self.ModParams, msg=163)
self.EffectsChecked(False)
'''
Add additional controls if JPG is selected
Certain file formats accept additional options which can be specified as keyword
arguments. Currently, only the 'jpeg' encoder accepts additional options, which are:
quality - Defines the quality of the JPEG encoder as an integer ranging from 1 to 100.
Defaults to 85. Please note that JPEG quality is not a percentage and
definitions of quality vary widely.
restart - Defines the restart interval for the JPEG encoder as a number of JPEG MCUs.
The actual restart interval used will be a multiple of the number of MCUs per row in the resulting image.
thumbnail - Defines the size and quality of the thumbnail to embed in the Exif
metadata. Specifying None disables thumbnail generation. Otherwise,
specify a tuple of (width, height, quality). Defaults to (64, 48, 35).
bayer - If True, the raw bayer data from the camera’s sensor is included in the
Exif metadata.
'''
#--------------- Flash Mode ---------------
f = MyLabelFrame(self,'LED and Flash mode',4,0,span=4)
#f.columnconfigure(3,weight=1)
self.LedOn = MyBooleanVar(True)
self.LedButton = ttk.Checkbutton(f,text='Led On (via GPIO pins)',
variable=self.LedOn, command=self.LedOnChecked)
self.LedButton.grid(row=0,column=0,sticky='NW',pady=5, columnspan=2)
ToolTip(self.LedButton,msg=102)
Label(f,text='Flash Mode:').grid(row=1,column=0,sticky='W')
b = MyStringVar('off')
self.FlashModeOffRadio = MyRadio(f,'Off (Default)','off',b,
self.FlashModeButton,1,1,'W',tip=180)
MyRadio(f,'Auto','auto',b,self.FlashModeButton,1,2,'W',tip=181)
MyRadio(f,'Select:','set',b,self.FlashModeButton,1,3,'W',tip=182)
# Use invoke() on radio button to force a command
self.FlashModeCombo = Combobox(f,state='readonly',width=10)
self.FlashModeCombo.grid(row=1,column=4,sticky='W')
self.FlashModeCombo.bind('<<ComboboxSelected>>',self.FlashModeChanged)
modes = list(self.camera.FLASH_MODES.keys())
modes.remove('off') # these two are handled by radio buttons
modes.remove('auto')
modes.sort() #cmp=lambda x,y: cmp(x.lower(),y.lower()))
self.FlashModeCombo['values'] = modes
self.FlashModeCombo.current(0)
self.FlashModeCombo.config(state='disabled')
ToolTip(self.FlashModeCombo,183)
self.FixedResolutionChanged(None) | [
"def",
"BuildPage",
"(",
"self",
")",
":",
"#### TODO: \tAdd Rotation. Cleanup and organize controls",
"#\t\t\tAdd handling of Image Effect Params",
"#----------- Select port for image captures ------------",
"f1",
"=",
"MyLabelFrame",
"(",
"self",
",",
"'Select port for image captures'",
",",
"0",
",",
"0",
",",
"span",
"=",
"2",
")",
"self",
".",
"UseVidPort",
"=",
"MyBooleanVar",
"(",
"False",
")",
"self",
".",
"UseRadio",
"=",
"MyRadio",
"(",
"f1",
",",
"'Use Still Port'",
",",
"False",
",",
"self",
".",
"UseVidPort",
",",
"self",
".",
"UseVideoPort",
",",
"0",
",",
"0",
",",
"'W'",
",",
"tip",
"=",
"100",
")",
"MyRadio",
"(",
"f1",
",",
"'Use Video Port'",
",",
"True",
",",
"self",
".",
"UseVidPort",
",",
"self",
".",
"UseVideoPort",
",",
"0",
",",
"1",
",",
"'W'",
",",
"tip",
"=",
"101",
")",
"f2",
"=",
"ttk",
".",
"Frame",
"(",
"f1",
")",
"# Sub frame",
"f2",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"0",
",",
"columnspan",
"=",
"4",
",",
"sticky",
"=",
"'NSEW'",
")",
"self",
".",
"VideoDenoise",
"=",
"MyBooleanVar",
"(",
"True",
")",
"b",
"=",
"ttk",
".",
"Checkbutton",
"(",
"f2",
",",
"text",
"=",
"'Video denoise'",
",",
"variable",
"=",
"self",
".",
"VideoDenoise",
",",
"command",
"=",
"self",
".",
"VideoDenoiseChecked",
")",
"b",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'NW'",
",",
"padx",
"=",
"5",
")",
"ToolTip",
"(",
"b",
",",
"msg",
"=",
"103",
")",
"self",
".",
"VideoStab",
"=",
"MyBooleanVar",
"(",
"False",
")",
"b",
"=",
"ttk",
".",
"Checkbutton",
"(",
"f2",
",",
"text",
"=",
"'Video stabilization'",
",",
"variable",
"=",
"self",
".",
"VideoStab",
",",
"command",
"=",
"self",
".",
"VideoStabChecked",
")",
"b",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"'NW'",
")",
"ToolTip",
"(",
"b",
",",
"msg",
"=",
"105",
")",
"self",
".",
"ImageDenoise",
"=",
"MyBooleanVar",
"(",
"True",
")",
"b",
"=",
"ttk",
".",
"Checkbutton",
"(",
"f2",
",",
"text",
"=",
"'Image denoise'",
",",
"variable",
"=",
"self",
".",
"ImageDenoise",
",",
"command",
"=",
"self",
".",
"ImageDenoiseChecked",
")",
"b",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"2",
",",
"sticky",
"=",
"'NW'",
",",
"padx",
"=",
"10",
")",
"ToolTip",
"(",
"b",
",",
"msg",
"=",
"104",
")",
"#--------------- Picture/Video Capture Size ---------------",
"f",
"=",
"MyLabelFrame",
"(",
"self",
",",
"'Picture/Video capture size in pixels'",
",",
"1",
",",
"0",
")",
"#f.columnconfigure(0,weight=1)",
"f1",
"=",
"ttk",
".",
"Frame",
"(",
"f",
")",
"# Sub frames to frame f",
"f1",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'NSEW'",
")",
"f1",
".",
"columnconfigure",
"(",
"1",
",",
"weight",
"=",
"1",
")",
"self",
".",
"UseFixedResolutions",
"=",
"BooleanVar",
"(",
")",
"self",
".",
"UseFixedResolutions",
".",
"set",
"(",
"True",
")",
"self",
".",
"UseFixedResRadio",
"=",
"ttk",
".",
"Radiobutton",
"(",
"f1",
",",
"text",
"=",
"'Use fixed:'",
",",
"variable",
"=",
"self",
".",
"UseFixedResolutions",
",",
"value",
"=",
"True",
",",
"command",
"=",
"self",
".",
"UseFixedResRadios",
",",
"padding",
"=",
"(",
"5",
",",
"5",
",",
"5",
",",
"5",
")",
")",
"ToolTip",
"(",
"self",
".",
"UseFixedResRadio",
",",
"120",
")",
"self",
".",
"UseFixedResRadio",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'NW'",
")",
"self",
".",
"FixedResolutionsCombo",
"=",
"Combobox",
"(",
"f1",
",",
"state",
"=",
"'readonly'",
",",
"width",
"=",
"25",
")",
"self",
".",
"FixedResolutionsCombo",
".",
"bind",
"(",
"'<<ComboboxSelected>>'",
",",
"self",
".",
"FixedResolutionChanged",
")",
"self",
".",
"FixedResolutionsCombo",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"1",
",",
"columnspan",
"=",
"3",
",",
"sticky",
"=",
"'W'",
")",
"ToolTip",
"(",
"self",
".",
"FixedResolutionsCombo",
",",
"121",
")",
"#------------ Capture Width and Height ----------------",
"# OrderedDict is used to ensure the keys stay in the same order as",
"# entered. I want the combobox to display in this order",
"#### TODO: \tMust check resolution and framerate and disable the Video",
"# \t\t\tbutton if we exceed limits of the modes",
"# Framerate 1-30 fps up to 1920x1080\t\t16:9 aspect ratio",
"# Framerate 1-15 fps up to 2592 x 1944\t\t 4:3 aspect ratio",
"# Framerate 0.1666 to 1 fps up to 2592 x 1944 4:3 aspect ratio",
"# Framerate 1-42 fps up t0 1296 x 972 \t\t 4:3 aspect ratio",
"# Framerate 1-49 fps up to 1296 x 730\t\t16:9 aspect ratio",
"# Framerate 42.1 - 60 fps to 640 x 480\t\t 4:3 aspect ratio",
"# Framerate 60.1 - 90 fps to 640 x 480\t\t 4:3 aspect ratio",
"self",
".",
"StandardResolutions",
"=",
"OrderedDict",
"(",
"[",
"(",
"'CGA'",
",",
"(",
"320",
",",
"200",
")",
")",
",",
"(",
"'QVGA'",
",",
"(",
"320",
",",
"240",
")",
")",
",",
"(",
"'VGA'",
",",
"(",
"640",
",",
"480",
")",
")",
",",
"(",
"'PAL'",
",",
"(",
"768",
",",
"576",
")",
")",
",",
"(",
"'480p'",
",",
"(",
"720",
",",
"480",
")",
")",
",",
"(",
"'576p'",
",",
"(",
"720",
",",
"576",
")",
")",
",",
"(",
"'WVGA'",
",",
"(",
"800",
",",
"480",
")",
")",
",",
"(",
"'SVGA'",
",",
"(",
"800",
",",
"600",
")",
")",
",",
"(",
"'FWVGA'",
",",
"(",
"854",
",",
"480",
")",
")",
",",
"(",
"'WSVGA'",
",",
"(",
"1024",
",",
"600",
")",
")",
",",
"(",
"'XGA'",
",",
"(",
"1024",
",",
"768",
")",
")",
",",
"(",
"'HD 720'",
",",
"(",
"1280",
",",
"720",
")",
")",
",",
"(",
"'WXGA_1'",
",",
"(",
"1280",
",",
"768",
")",
")",
",",
"(",
"'WXGA_2'",
",",
"(",
"1280",
",",
"800",
")",
")",
",",
"(",
"'SXGA'",
",",
"(",
"1280",
",",
"1024",
")",
")",
",",
"(",
"'SXGA+'",
",",
"(",
"1400",
",",
"1050",
")",
")",
",",
"(",
"'UXGA'",
",",
"(",
"1600",
",",
"1200",
")",
")",
",",
"(",
"'WSXGA+'",
",",
"(",
"1680",
",",
"1050",
")",
")",
",",
"(",
"'HD 1080'",
",",
"(",
"1920",
",",
"1080",
")",
")",
",",
"(",
"'WUXGA'",
",",
"(",
"1920",
",",
"1200",
")",
")",
",",
"(",
"'2K'",
",",
"(",
"2048",
",",
"1080",
")",
")",
",",
"(",
"'QXGA'",
",",
"(",
"2048",
",",
"1536",
")",
")",
",",
"(",
"'WQXGA'",
",",
"(",
"2560",
",",
"1600",
")",
")",
",",
"(",
"'MAX Resolution'",
",",
"(",
"2592",
",",
"1944",
")",
")",
",",
"]",
")",
"vals",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"StandardResolutions",
".",
"keys",
"(",
")",
":",
"vals",
".",
"append",
"(",
"'%s: (%dx%d)'",
"%",
"(",
"key",
",",
"# Tabs not working?!!",
"self",
".",
"StandardResolutions",
"[",
"key",
"]",
"[",
"0",
"]",
",",
"self",
".",
"StandardResolutions",
"[",
"key",
"]",
"[",
"1",
"]",
")",
")",
"self",
".",
"FixedResolutionsCombo",
"[",
"'values'",
"]",
"=",
"vals",
"self",
".",
"FixedResolutionsCombo",
".",
"current",
"(",
"10",
")",
"f2",
"=",
"ttk",
".",
"Frame",
"(",
"f",
")",
"# subframe to frame f",
"f2",
".",
"grid",
"(",
"row",
"=",
"2",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'NSEW'",
")",
"f2",
".",
"columnconfigure",
"(",
"2",
",",
"weight",
"=",
"1",
")",
"f2",
".",
"columnconfigure",
"(",
"4",
",",
"weight",
"=",
"1",
")",
"b2",
"=",
"ttk",
".",
"Radiobutton",
"(",
"f2",
",",
"text",
"=",
"'Roll your own:'",
",",
"variable",
"=",
"self",
".",
"UseFixedResolutions",
",",
"value",
"=",
"False",
",",
"command",
"=",
"self",
".",
"UseFixedResRadios",
",",
"padding",
"=",
"(",
"5",
",",
"5",
",",
"5",
",",
"5",
")",
")",
"b2",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'NW'",
")",
"ToolTip",
"(",
"b2",
",",
"122",
")",
"Label",
"(",
"f2",
",",
"text",
"=",
"\"Width:\"",
",",
"anchor",
"=",
"E",
")",
".",
"grid",
"(",
"column",
"=",
"1",
",",
"row",
"=",
"1",
",",
"sticky",
"=",
"'E'",
",",
"ipadx",
"=",
"3",
",",
"ipady",
"=",
"3",
")",
"Widths",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"82",
")",
":",
"Widths",
".",
"append",
"(",
"32",
"*",
"i",
")",
"# Widths can be in 32 byte increments",
"self",
".",
"cb",
"=",
"MyComboBox",
"(",
"f2",
",",
"Widths",
",",
"current",
"=",
"10",
",",
"callback",
"=",
"self",
".",
"ResolutionChanged",
",",
"width",
"=",
"5",
",",
"row",
"=",
"1",
",",
"col",
"=",
"2",
",",
"sticky",
"=",
"'W'",
",",
"state",
"=",
"'disabled'",
",",
"tip",
"=",
"123",
")",
"Label",
"(",
"f2",
",",
"text",
"=",
"\"Height:\"",
",",
"anchor",
"=",
"E",
")",
".",
"grid",
"(",
"column",
"=",
"3",
",",
"row",
"=",
"1",
",",
"sticky",
"=",
"'W'",
",",
"ipadx",
"=",
"5",
",",
"ipady",
"=",
"3",
")",
"Heights",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"123",
")",
":",
"Heights",
".",
"append",
"(",
"16",
"*",
"i",
")",
"# heights in 16 byte increments",
"self",
".",
"cb1",
"=",
"MyComboBox",
"(",
"f2",
",",
"Heights",
",",
"current",
"=",
"10",
",",
"callback",
"=",
"self",
".",
"ResolutionChanged",
",",
"width",
"=",
"5",
",",
"row",
"=",
"1",
",",
"col",
"=",
"4",
",",
"sticky",
"=",
"'W'",
",",
"state",
"=",
"'disabled'",
",",
"tip",
"=",
"124",
")",
"ttk",
".",
"Label",
"(",
"f2",
",",
"text",
"=",
"'Actual:'",
")",
".",
"grid",
"(",
"row",
"=",
"2",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"'E'",
")",
"self",
".",
"WidthLabel",
"=",
"ttk",
".",
"Label",
"(",
"f2",
",",
"style",
"=",
"'DataLabel.TLabel'",
")",
"self",
".",
"WidthLabel",
".",
"grid",
"(",
"row",
"=",
"2",
",",
"column",
"=",
"2",
",",
"sticky",
"=",
"'W'",
")",
"ToolTip",
"(",
"self",
".",
"WidthLabel",
",",
"125",
")",
"ttk",
".",
"Label",
"(",
"f2",
",",
"text",
"=",
"'Actual:'",
")",
".",
"grid",
"(",
"row",
"=",
"2",
",",
"column",
"=",
"3",
",",
"sticky",
"=",
"'E'",
")",
"self",
".",
"HeightLabel",
"=",
"ttk",
".",
"Label",
"(",
"f2",
",",
"style",
"=",
"'DataLabel.TLabel'",
")",
"self",
".",
"HeightLabel",
".",
"grid",
"(",
"row",
"=",
"2",
",",
"column",
"=",
"4",
",",
"sticky",
"=",
"'W'",
")",
"ToolTip",
"(",
"self",
".",
"HeightLabel",
",",
"126",
")",
"Separator",
"(",
"f",
",",
"orient",
"=",
"HORIZONTAL",
")",
".",
"grid",
"(",
"pady",
"=",
"5",
",",
"row",
"=",
"3",
",",
"column",
"=",
"0",
",",
"columnspan",
"=",
"4",
",",
"sticky",
"=",
"'EW'",
")",
"#--------------- Zoom Region Before ----------------",
"f4",
"=",
"MyLabelFrame",
"(",
"f",
",",
"'Zoom region of interest before taking '",
"+",
"'picture/video'",
",",
"4",
",",
"0",
")",
"#f4.columnconfigure(1,weight=1)",
"#f4.columnconfigure(3,weight=1)",
"Label",
"(",
"f4",
",",
"text",
"=",
"'X:'",
")",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'E'",
")",
"self",
".",
"Xzoom",
"=",
"ttk",
".",
"Scale",
"(",
"f4",
",",
"from_",
"=",
"0.0",
",",
"to",
"=",
"0.94",
",",
"orient",
"=",
"'horizontal'",
")",
"self",
".",
"Xzoom",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"'W'",
",",
"padx",
"=",
"5",
",",
"pady",
"=",
"3",
")",
"self",
".",
"Xzoom",
".",
"set",
"(",
"0.0",
")",
"ToolTip",
"(",
"self",
".",
"Xzoom",
",",
"130",
")",
"Label",
"(",
"f4",
",",
"text",
"=",
"'Y:'",
")",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"2",
",",
"sticky",
"=",
"'E'",
")",
"self",
".",
"Yzoom",
"=",
"ttk",
".",
"Scale",
"(",
"f4",
",",
"from_",
"=",
"0.0",
",",
"to",
"=",
"0.94",
",",
"orient",
"=",
"'horizontal'",
")",
"self",
".",
"Yzoom",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"3",
",",
"sticky",
"=",
"'W'",
",",
"padx",
"=",
"5",
",",
"pady",
"=",
"3",
")",
"self",
".",
"Yzoom",
".",
"set",
"(",
"0.0",
")",
"ToolTip",
"(",
"self",
".",
"Yzoom",
",",
"131",
")",
"Label",
"(",
"f4",
",",
"text",
"=",
"'Width:'",
")",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'E'",
")",
"self",
".",
"Widthzoom",
"=",
"ttk",
".",
"Scale",
"(",
"f4",
",",
"from_",
"=",
"0.05",
",",
"to",
"=",
"1.0",
",",
"orient",
"=",
"'horizontal'",
")",
"self",
".",
"Widthzoom",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"'W'",
",",
"padx",
"=",
"5",
",",
"pady",
"=",
"3",
")",
"self",
".",
"Widthzoom",
".",
"set",
"(",
"1.0",
")",
"ToolTip",
"(",
"self",
".",
"Widthzoom",
",",
"132",
")",
"Label",
"(",
"f4",
",",
"text",
"=",
"'Height:'",
")",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"2",
",",
"sticky",
"=",
"'E'",
")",
"self",
".",
"Heightzoom",
"=",
"ttk",
".",
"Scale",
"(",
"f4",
",",
"from_",
"=",
"0.05",
",",
"to",
"=",
"1.0",
",",
"orient",
"=",
"'horizontal'",
")",
"self",
".",
"Heightzoom",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"3",
",",
"sticky",
"=",
"'W'",
",",
"padx",
"=",
"5",
",",
"pady",
"=",
"3",
")",
"self",
".",
"Heightzoom",
".",
"set",
"(",
"1.0",
")",
"ToolTip",
"(",
"self",
".",
"Heightzoom",
",",
"133",
")",
"# WLW THIS IS A PROBLEM",
"image",
"=",
"PIL",
".",
"Image",
".",
"open",
"(",
"'Assets/reset.png'",
")",
"#.resize((16,16))",
"self",
".",
"resetImage",
"=",
"GetPhotoImage",
"(",
"image",
".",
"resize",
"(",
"(",
"16",
",",
"16",
")",
")",
")",
"self",
".",
"ResetZoomButton",
"=",
"ttk",
".",
"Button",
"(",
"f4",
",",
"image",
"=",
"self",
".",
"resetImage",
",",
"command",
"=",
"self",
".",
"ZoomReset",
")",
"self",
".",
"ResetZoomButton",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"4",
",",
"rowspan",
"=",
"2",
",",
"sticky",
"=",
"'W'",
")",
"ToolTip",
"(",
"self",
".",
"ResetZoomButton",
",",
"134",
")",
"self",
".",
"Xzoom",
".",
"config",
"(",
"command",
"=",
"lambda",
"newval",
",",
"widget",
"=",
"self",
".",
"Xzoom",
":",
"self",
".",
"Zoom",
"(",
"newval",
",",
"widget",
")",
")",
"self",
".",
"Yzoom",
".",
"config",
"(",
"command",
"=",
"lambda",
"newval",
",",
"widget",
"=",
"self",
".",
"Yzoom",
":",
"self",
".",
"Zoom",
"(",
"newval",
",",
"widget",
")",
")",
"self",
".",
"Widthzoom",
".",
"config",
"(",
"command",
"=",
"lambda",
"newval",
",",
"widget",
"=",
"self",
".",
"Widthzoom",
":",
"self",
".",
"Zoom",
"(",
"newval",
",",
"widget",
")",
")",
"self",
".",
"Heightzoom",
".",
"config",
"(",
"command",
"=",
"lambda",
"newval",
",",
"widget",
"=",
"self",
".",
"Heightzoom",
":",
"self",
".",
"Zoom",
"(",
"newval",
",",
"widget",
")",
")",
"Separator",
"(",
"f",
",",
"orient",
"=",
"HORIZONTAL",
")",
".",
"grid",
"(",
"pady",
"=",
"5",
",",
"row",
"=",
"5",
",",
"column",
"=",
"0",
",",
"columnspan",
"=",
"3",
",",
"sticky",
"=",
"'EW'",
")",
"#--------------- Resize Image After ----------------",
"f4",
"=",
"MyLabelFrame",
"(",
"f",
",",
"'Resize image after taking picture/video'",
",",
"6",
",",
"0",
")",
"#f4.columnconfigure(3,weight=1)",
"#f4.columnconfigure(5,weight=1)",
"b",
"=",
"MyBooleanVar",
"(",
"False",
")",
"self",
".",
"ResizeAfterNone",
"=",
"MyRadio",
"(",
"f4",
",",
"'None (Default)'",
",",
"False",
",",
"b",
",",
"self",
".",
"AllowImageResizeAfter",
",",
"0",
",",
"0",
",",
"'W'",
",",
"pad",
"=",
"(",
"0",
",",
"5",
",",
"0",
",",
"5",
")",
",",
"tip",
"=",
"140",
")",
"MyRadio",
"(",
"f4",
",",
"'Resize'",
",",
"True",
",",
"b",
",",
"self",
".",
"AllowImageResizeAfter",
",",
"0",
",",
"1",
",",
"'W'",
",",
"pad",
"=",
"(",
"5",
",",
"5",
",",
"0",
",",
"5",
")",
",",
"tip",
"=",
"141",
")",
"Label",
"(",
"f4",
",",
"text",
"=",
"\"Width:\"",
",",
"anchor",
"=",
"E",
")",
".",
"grid",
"(",
"column",
"=",
"2",
",",
"row",
"=",
"0",
",",
"sticky",
"=",
"'E'",
",",
"ipadx",
"=",
"3",
",",
"ipady",
"=",
"3",
")",
"self",
".",
"resizeWidthAfterCombo",
"=",
"MyComboBox",
"(",
"f4",
",",
"Widths",
",",
"current",
"=",
"10",
",",
"callback",
"=",
"self",
".",
"ResizeAfterChanged",
",",
"width",
"=",
"5",
",",
"row",
"=",
"0",
",",
"col",
"=",
"3",
",",
"sticky",
"=",
"'W'",
",",
"state",
"=",
"'disabled'",
",",
"tip",
"=",
"142",
")",
"Label",
"(",
"f4",
",",
"text",
"=",
"\"Height:\"",
",",
"anchor",
"=",
"E",
")",
".",
"grid",
"(",
"column",
"=",
"4",
",",
"row",
"=",
"0",
",",
"sticky",
"=",
"'W'",
",",
"ipadx",
"=",
"5",
",",
"ipady",
"=",
"3",
")",
"self",
".",
"resizeHeightAfterCombo",
"=",
"MyComboBox",
"(",
"f4",
",",
"Heights",
",",
"current",
"=",
"10",
",",
"callback",
"=",
"self",
".",
"ResizeAfterChanged",
",",
"width",
"=",
"5",
",",
"row",
"=",
"0",
",",
"col",
"=",
"5",
",",
"sticky",
"=",
"'W'",
",",
"state",
"=",
"'disabled'",
",",
"tip",
"=",
"143",
")",
"self",
".",
"resizeAfter",
"=",
"None",
"#--------------- Quick Adjustments ----------------",
"f",
"=",
"MyLabelFrame",
"(",
"self",
",",
"'Quick adjustments'",
",",
"2",
",",
"0",
")",
"#f.columnconfigure(2,weight=1)",
"#-Brightness",
"self",
".",
"brightLabel",
",",
"self",
".",
"brightness",
",",
"val",
"=",
"self",
".",
"SetupLabelCombo",
"(",
"f",
",",
"'Brightness:'",
",",
"0",
",",
"0",
",",
"0",
",",
"100",
",",
"self",
".",
"CameraBrightnessChanged",
",",
"self",
".",
"camera",
".",
"brightness",
")",
"self",
".",
"CameraBrightnessChanged",
"(",
"val",
")",
"ToolTip",
"(",
"self",
".",
"brightness",
",",
"msg",
"=",
"150",
")",
"#-Contrast",
"self",
".",
"contrastLabel",
",",
"self",
".",
"contrast",
",",
"val",
"=",
"self",
".",
"SetupLabelCombo",
"(",
"f",
",",
"'Contrast:'",
",",
"0",
",",
"3",
",",
"-",
"100",
",",
"100",
",",
"self",
".",
"ContrastChanged",
",",
"self",
".",
"camera",
".",
"contrast",
")",
"self",
".",
"ContrastChanged",
"(",
"val",
")",
"ToolTip",
"(",
"self",
".",
"contrast",
",",
"msg",
"=",
"151",
")",
"#-Saturation",
"self",
".",
"saturationLabel",
",",
"self",
".",
"saturation",
",",
"val",
"=",
"self",
".",
"SetupLabelCombo",
"(",
"f",
",",
"'Saturation:'",
",",
"1",
",",
"0",
",",
"-",
"100",
",",
"100",
",",
"self",
".",
"SaturationChanged",
",",
"self",
".",
"camera",
".",
"saturation",
",",
"label",
"=",
"'Sat'",
")",
"self",
".",
"SaturationChanged",
"(",
"val",
")",
"ToolTip",
"(",
"self",
".",
"saturation",
",",
"msg",
"=",
"152",
")",
"#-Sharpness",
"self",
".",
"sharpnessLabel",
",",
"self",
".",
"sharpness",
",",
"val",
"=",
"self",
".",
"SetupLabelCombo",
"(",
"f",
",",
"'Sharpness:'",
",",
"1",
",",
"3",
",",
"-",
"100",
",",
"100",
",",
"self",
".",
"SharpnessChanged",
",",
"self",
".",
"camera",
".",
"sharpness",
")",
"self",
".",
"SharpnessChanged",
"(",
"val",
")",
"ToolTip",
"(",
"self",
".",
"sharpness",
",",
"msg",
"=",
"153",
")",
"#-Reset",
"#self.ResetGeneralButton = Button(f,image=self.resetImage,width=5,",
"#command=self.ResetGeneralSliders)",
"#self.ResetGeneralButton.grid(row=4,column=2,sticky='W',padx=5)",
"#ToolTip(self.ResetGeneralButton,msg=154)",
"#--------------- Image Effects ----------------",
"f",
"=",
"MyLabelFrame",
"(",
"self",
",",
"'Preprogrammed image effects'",
",",
"3",
",",
"0",
")",
"#f.columnconfigure(2,weight=1)",
"v",
"=",
"MyBooleanVar",
"(",
"False",
")",
"self",
".",
"NoEffectsRadio",
"=",
"MyRadio",
"(",
"f",
",",
"'None (Default)'",
",",
"False",
",",
"v",
",",
"self",
".",
"EffectsChecked",
",",
"0",
",",
"0",
",",
"'W'",
",",
"tip",
"=",
"160",
")",
"MyRadio",
"(",
"f",
",",
"'Select effect:'",
",",
"True",
",",
"v",
",",
"self",
".",
"EffectsChecked",
",",
"0",
",",
"1",
",",
"'W'",
",",
"tip",
"=",
"161",
")",
"self",
".",
"effects",
"=",
"Combobox",
"(",
"f",
",",
"height",
"=",
"15",
",",
"width",
"=",
"10",
",",
"state",
"=",
"'readonly'",
")",
"#,width=15)",
"self",
".",
"effects",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"2",
",",
"sticky",
"=",
"'W'",
")",
"effects",
"=",
"list",
"(",
"self",
".",
"camera",
".",
"IMAGE_EFFECTS",
".",
"keys",
"(",
")",
")",
"# python 3 workaround",
"effects",
".",
"remove",
"(",
"'none'",
")",
"effects",
".",
"sort",
"(",
")",
"#cmp=lambda x,y: cmp(x.lower(),y.lower())) # not python 3",
"self",
".",
"effects",
"[",
"'values'",
"]",
"=",
"effects",
"self",
".",
"effects",
".",
"current",
"(",
"0",
")",
"self",
".",
"effects",
".",
"bind",
"(",
"'<<ComboboxSelected>>'",
",",
"self",
".",
"EffectsChanged",
")",
"ToolTip",
"(",
"self",
".",
"effects",
",",
"msg",
"=",
"162",
")",
"self",
".",
"ModParams",
"=",
"ttk",
".",
"Button",
"(",
"f",
",",
"text",
"=",
"'Params...'",
",",
"command",
"=",
"self",
".",
"ModifyEffectsParamsPressed",
",",
"underline",
"=",
"0",
",",
"padding",
"=",
"(",
"5",
",",
"3",
",",
"5",
",",
"3",
")",
",",
"width",
"=",
"8",
")",
"self",
".",
"ModParams",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"3",
",",
"sticky",
"=",
"EW",
",",
"padx",
"=",
"5",
")",
"ToolTip",
"(",
"self",
".",
"ModParams",
",",
"msg",
"=",
"163",
")",
"self",
".",
"EffectsChecked",
"(",
"False",
")",
"#--------------- Flash Mode ---------------",
"f",
"=",
"MyLabelFrame",
"(",
"self",
",",
"'LED and Flash mode'",
",",
"4",
",",
"0",
",",
"span",
"=",
"4",
")",
"#f.columnconfigure(3,weight=1)",
"self",
".",
"LedOn",
"=",
"MyBooleanVar",
"(",
"True",
")",
"self",
".",
"LedButton",
"=",
"ttk",
".",
"Checkbutton",
"(",
"f",
",",
"text",
"=",
"'Led On (via GPIO pins)'",
",",
"variable",
"=",
"self",
".",
"LedOn",
",",
"command",
"=",
"self",
".",
"LedOnChecked",
")",
"self",
".",
"LedButton",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'NW'",
",",
"pady",
"=",
"5",
",",
"columnspan",
"=",
"2",
")",
"ToolTip",
"(",
"self",
".",
"LedButton",
",",
"msg",
"=",
"102",
")",
"Label",
"(",
"f",
",",
"text",
"=",
"'Flash Mode:'",
")",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"'W'",
")",
"b",
"=",
"MyStringVar",
"(",
"'off'",
")",
"self",
".",
"FlashModeOffRadio",
"=",
"MyRadio",
"(",
"f",
",",
"'Off (Default)'",
",",
"'off'",
",",
"b",
",",
"self",
".",
"FlashModeButton",
",",
"1",
",",
"1",
",",
"'W'",
",",
"tip",
"=",
"180",
")",
"MyRadio",
"(",
"f",
",",
"'Auto'",
",",
"'auto'",
",",
"b",
",",
"self",
".",
"FlashModeButton",
",",
"1",
",",
"2",
",",
"'W'",
",",
"tip",
"=",
"181",
")",
"MyRadio",
"(",
"f",
",",
"'Select:'",
",",
"'set'",
",",
"b",
",",
"self",
".",
"FlashModeButton",
",",
"1",
",",
"3",
",",
"'W'",
",",
"tip",
"=",
"182",
")",
"# Use invoke() on radio button to force a command",
"self",
".",
"FlashModeCombo",
"=",
"Combobox",
"(",
"f",
",",
"state",
"=",
"'readonly'",
",",
"width",
"=",
"10",
")",
"self",
".",
"FlashModeCombo",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"4",
",",
"sticky",
"=",
"'W'",
")",
"self",
".",
"FlashModeCombo",
".",
"bind",
"(",
"'<<ComboboxSelected>>'",
",",
"self",
".",
"FlashModeChanged",
")",
"modes",
"=",
"list",
"(",
"self",
".",
"camera",
".",
"FLASH_MODES",
".",
"keys",
"(",
")",
")",
"modes",
".",
"remove",
"(",
"'off'",
")",
"# these two are handled by radio buttons",
"modes",
".",
"remove",
"(",
"'auto'",
")",
"modes",
".",
"sort",
"(",
")",
"#cmp=lambda x,y: cmp(x.lower(),y.lower()))",
"self",
".",
"FlashModeCombo",
"[",
"'values'",
"]",
"=",
"modes",
"self",
".",
"FlashModeCombo",
".",
"current",
"(",
"0",
")",
"self",
".",
"FlashModeCombo",
".",
"config",
"(",
"state",
"=",
"'disabled'",
")",
"ToolTip",
"(",
"self",
".",
"FlashModeCombo",
",",
"183",
")",
"self",
".",
"FixedResolutionChanged",
"(",
"None",
")"
] | https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/BasicControls.py#L52-L340 |
||
Billwilliams1952/PiCameraApp | 61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0 | Source/Exposure.py | python | Exposure.ValidateEntry | ( self, entry, minVal, maxVal ) | return num | Change how the edit fields work. Allow a '/' in the edit field to
denote a fraction.
Split on '/' and evaluate each side. Note, if '<num> /' then
num is evalulated since 'den' is empty | Change how the edit fields work. Allow a '/' in the edit field to
denote a fraction.
Split on '/' and evaluate each side. Note, if '<num> /' then
num is evalulated since 'den' is empty | [
"Change",
"how",
"the",
"edit",
"fields",
"work",
".",
"Allow",
"a",
"/",
"in",
"the",
"edit",
"field",
"to",
"denote",
"a",
"fraction",
".",
"Split",
"on",
"/",
"and",
"evaluate",
"each",
"side",
".",
"Note",
"if",
"<num",
">",
"/",
"then",
"num",
"is",
"evalulated",
"since",
"den",
"is",
"empty"
] | def ValidateEntry ( self, entry, minVal, maxVal ):
'''
Change how the edit fields work. Allow a '/' in the edit field to
denote a fraction.
Split on '/' and evaluate each side. Note, if '<num> /' then
num is evalulated since 'den' is empty
'''
vals = entry.split('/',1) # entry is text
val = vals[0].strip()
try: num = float(val)
except: num = None
else:
if len(vals) > 1:
val = vals[1].strip()
if val:
try: den = float(val)
except: num = None
else:
if den > 0: num = num / den
else: num = None
if num is not None:
num = num if num >= minVal and num <= maxVal else None
self.FrameRate.config(style='RedMessage.TLabel' if num is None \
else 'DataLabel.TLabel')
return num | [
"def",
"ValidateEntry",
"(",
"self",
",",
"entry",
",",
"minVal",
",",
"maxVal",
")",
":",
"vals",
"=",
"entry",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"# entry is text",
"val",
"=",
"vals",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"try",
":",
"num",
"=",
"float",
"(",
"val",
")",
"except",
":",
"num",
"=",
"None",
"else",
":",
"if",
"len",
"(",
"vals",
")",
">",
"1",
":",
"val",
"=",
"vals",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"if",
"val",
":",
"try",
":",
"den",
"=",
"float",
"(",
"val",
")",
"except",
":",
"num",
"=",
"None",
"else",
":",
"if",
"den",
">",
"0",
":",
"num",
"=",
"num",
"/",
"den",
"else",
":",
"num",
"=",
"None",
"if",
"num",
"is",
"not",
"None",
":",
"num",
"=",
"num",
"if",
"num",
">=",
"minVal",
"and",
"num",
"<=",
"maxVal",
"else",
"None",
"self",
".",
"FrameRate",
".",
"config",
"(",
"style",
"=",
"'RedMessage.TLabel'",
"if",
"num",
"is",
"None",
"else",
"'DataLabel.TLabel'",
")",
"return",
"num"
] | https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Exposure.py#L473-L497 |
|
Billwilliams1952/PiCameraApp | 61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0 | Source/Tooltip.py | python | ToolTip.__init__ | ( self, wdgt, msg=None, msgFunc=None, follow=1 ) | Initialize the ToolTip
Arguments:
wdgt: The widget to which this ToolTip is assigned
msg: A static string message assigned to the ToolTip
if msg istype integer - search for text in TipLines
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides | Initialize the ToolTip
Arguments:
wdgt: The widget to which this ToolTip is assigned
msg: A static string message assigned to the ToolTip
if msg istype integer - search for text in TipLines
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides | [
"Initialize",
"the",
"ToolTip",
"Arguments",
":",
"wdgt",
":",
"The",
"widget",
"to",
"which",
"this",
"ToolTip",
"is",
"assigned",
"msg",
":",
"A",
"static",
"string",
"message",
"assigned",
"to",
"the",
"ToolTip",
"if",
"msg",
"istype",
"integer",
"-",
"search",
"for",
"text",
"in",
"TipLines",
"msgFunc",
":",
"A",
"function",
"that",
"retrieves",
"a",
"string",
"to",
"use",
"as",
"the",
"ToolTip",
"text",
"delay",
":",
"The",
"delay",
"in",
"seconds",
"before",
"the",
"ToolTip",
"appears",
"(",
"may",
"be",
"float",
")",
"follow",
":",
"If",
"True",
"the",
"ToolTip",
"follows",
"motion",
"otherwise",
"hides"
] | def __init__( self, wdgt, msg=None, msgFunc=None, follow=1 ):
"""
Initialize the ToolTip
Arguments:
wdgt: The widget to which this ToolTip is assigned
msg: A static string message assigned to the ToolTip
if msg istype integer - search for text in TipLines
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides
"""
self.wdgt = wdgt
# The parent of the ToolTip is the parent of the ToolTips widget
self.parent = self.wdgt.master
# Initalise the Toplevel
Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 )
self.withdraw() # Hide initially
# The ToolTip Toplevel should have no frame or title bar
self.overrideredirect( True )
# The msgVar will contain the text displayed by the ToolTip
self.msgVar = StringVar()
self.TipID = None
self.TipNumText = ""
try:
if msg is None:
self.msgVar.set('No tooltip provided')
elif type(msg) is int: # lookup tooltip text in file
self.TipID = msg
self.msgVar.set(ToolTip.GetTooltipText(msg))
self.TipNumText = "Tip number %d\n\n" % self.TipID
else: # assume a string is passed
self.msgVar.set( msg )
except:
self.msgVar.set('ERROR getting tooltip')
self.msgFunc = msgFunc # call this function to return tip text
self.follow = follow # move tip if mouse moves
self.visible = 0
self.lastMotion = 0
# The test of the ToolTip is displayed in a Message widget
Message( self, textvariable=self.msgVar, bg='#FFFFDD',
aspect=250 ).grid()
# Add bindings to the widget. This will NOT override bindings
# that the widget already has
self.wdgt.bind( '<Enter>', self.spawn, '+' )
self.wdgt.bind( '<Leave>', self.hide, '+' )
self.wdgt.bind( '<Motion>', self.move, '+' ) | [
"def",
"__init__",
"(",
"self",
",",
"wdgt",
",",
"msg",
"=",
"None",
",",
"msgFunc",
"=",
"None",
",",
"follow",
"=",
"1",
")",
":",
"self",
".",
"wdgt",
"=",
"wdgt",
"# The parent of the ToolTip is the parent of the ToolTips widget",
"self",
".",
"parent",
"=",
"self",
".",
"wdgt",
".",
"master",
"# Initalise the Toplevel",
"Toplevel",
".",
"__init__",
"(",
"self",
",",
"self",
".",
"parent",
",",
"bg",
"=",
"'black'",
",",
"padx",
"=",
"1",
",",
"pady",
"=",
"1",
")",
"self",
".",
"withdraw",
"(",
")",
"# Hide initially",
"# The ToolTip Toplevel should have no frame or title bar",
"self",
".",
"overrideredirect",
"(",
"True",
")",
"# The msgVar will contain the text displayed by the ToolTip",
"self",
".",
"msgVar",
"=",
"StringVar",
"(",
")",
"self",
".",
"TipID",
"=",
"None",
"self",
".",
"TipNumText",
"=",
"\"\"",
"try",
":",
"if",
"msg",
"is",
"None",
":",
"self",
".",
"msgVar",
".",
"set",
"(",
"'No tooltip provided'",
")",
"elif",
"type",
"(",
"msg",
")",
"is",
"int",
":",
"# lookup tooltip text in file",
"self",
".",
"TipID",
"=",
"msg",
"self",
".",
"msgVar",
".",
"set",
"(",
"ToolTip",
".",
"GetTooltipText",
"(",
"msg",
")",
")",
"self",
".",
"TipNumText",
"=",
"\"Tip number %d\\n\\n\"",
"%",
"self",
".",
"TipID",
"else",
":",
"# assume a string is passed",
"self",
".",
"msgVar",
".",
"set",
"(",
"msg",
")",
"except",
":",
"self",
".",
"msgVar",
".",
"set",
"(",
"'ERROR getting tooltip'",
")",
"self",
".",
"msgFunc",
"=",
"msgFunc",
"# call this function to return tip text",
"self",
".",
"follow",
"=",
"follow",
"# move tip if mouse moves",
"self",
".",
"visible",
"=",
"0",
"self",
".",
"lastMotion",
"=",
"0",
"# The test of the ToolTip is displayed in a Message widget",
"Message",
"(",
"self",
",",
"textvariable",
"=",
"self",
".",
"msgVar",
",",
"bg",
"=",
"'#FFFFDD'",
",",
"aspect",
"=",
"250",
")",
".",
"grid",
"(",
")",
"# Add bindings to the widget. This will NOT override bindings",
"# that the widget already has",
"self",
".",
"wdgt",
".",
"bind",
"(",
"'<Enter>'",
",",
"self",
".",
"spawn",
",",
"'+'",
")",
"self",
".",
"wdgt",
".",
"bind",
"(",
"'<Leave>'",
",",
"self",
".",
"hide",
",",
"'+'",
")",
"self",
".",
"wdgt",
".",
"bind",
"(",
"'<Motion>'",
",",
"self",
".",
"move",
",",
"'+'",
")"
] | https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Tooltip.py#L102-L147 |