fishyboteso/fishy/helper/luaparser.py

80 lines
2.5 KiB
Python
Raw Normal View History

2021-04-09 18:50:53 +00:00
import logging
2021-05-09 07:05:51 +00:00
import os
2021-04-09 18:50:53 +00:00
from math import floor
2021-05-09 07:05:51 +00:00
2021-04-09 18:50:53 +00:00
from .helper import get_savedvarsdir
def _sv_parser(path):
try:
with open(path, "r") as f:
lua = f.read()
"""
bring lua saved-var file into a useable format:
- one line per expression (add \n where needed)
- remove all redundant characters
- make lowercase, split into list of expressions
- remove empty expressions
EXPRESSIONS: A) List-Start "name=", B) Variable assignment "name=val", C) List End "}"
"""
2021-05-09 09:09:26 +00:00
for old, new in ((",", "\n"), ("{", "{\n"), ("}", "}\n"), ("{", ""), (",", ""), ("[", ""), ("]", ""), ('"', ""), (" ", "")):
2021-05-07 12:07:09 +00:00
lua = lua.replace(old, new)
2021-04-09 18:50:53 +00:00
lua = lua.lower().split("\n")
lua = [expression for expression in lua if expression]
"""
the lua saved-var file is parsed to a tree of dicts
each line represents either one node in the tree or the end of a subtree
the last symbol of each line decides the type of the node (branch vertex or leaf)
"""
stack = []
2021-05-09 09:09:26 +00:00
root = (dict(), "root")
2021-04-09 18:50:53 +00:00
stack.append(root)
for line in lua:
if line == "":
break
2021-05-09 09:09:26 +00:00
if line[-1] == '=': #subtree start
2021-04-09 18:50:53 +00:00
t = dict()
tname = line.split("=")[0]
2021-05-09 09:09:26 +00:00
stack.append((t, tname))
elif line[-1] == '}': #subtree end
2021-04-09 18:50:53 +00:00
t = stack.pop()
tp = stack.pop()
tp[0][t[1]] = t[0]
stack.append(tp)
2021-05-09 09:09:26 +00:00
else: #new element in tree
name, val = line.split("=")
2021-04-09 18:50:53 +00:00
t = stack.pop()
t[0][name] = val
stack.append(t)
return root[0]
except Exception as ex:
logging.error("Error: '" + str(ex) + "' occured, while parsing ESO variables.")
return None
2021-05-07 12:07:09 +00:00
def sv_color_extract(Colors):
2021-04-09 18:50:53 +00:00
root = _sv_parser(os.path.join(get_savedvarsdir(), "Chalutier.lua"))
if root == None:
2021-05-07 12:07:09 +00:00
return Colors
2021-04-09 18:50:53 +00:00
for i in range(4):
name, root = root.popitem()
colors = []
for i in root["colors"]:
"""
ingame representation of colors range from 0 to 1 in float
these values are scaled by 255
"""
2021-05-09 09:09:26 +00:00
rgb = [
floor(float(root["colors"][i]["r"]) * 255),
floor(float(root["colors"][i]["g"]) * 255),
floor(float(root["colors"][i]["b"]) * 255)
2021-04-09 18:50:53 +00:00
]
colors.append(rgb)
2021-05-09 09:09:26 +00:00
for i, c in enumerate(Colors):
2021-05-07 12:07:09 +00:00
Colors[c] = colors[i]
return Colors