Merge pull request #30 from Faraphel/master

pushing small modification since v0.11 to dev branch
This commit is contained in:
Faraphel 2022-06-07 19:22:37 +02:00 committed by GitHub
commit 9cac274a4f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 117 additions and 281 deletions

View file

@ -1,17 +0,0 @@
import os
import json
os.chdir("..")
from source.CT_Config import CT_Config
ct_config = CT_Config()
ct_config.load_ctconfig_file()
with open(r"..\GameReview\MKWF\old_notation.json", "r", encoding="utf8") as f:
old_n = json.load(f)
track_list = list(filter(lambda x: x.since_version == "0.10", ct_config.unordered_tracks))
for track in track_list:
old_n[track.sha1] = {"216179546427359232": track.score}
with open(r"..\GameReview\MKWF\old_notation.json", "w", encoding="utf8") as f:
json.dump(old_n, f, ensure_ascii=False)

View file

@ -1,166 +0,0 @@
"""
This script allow you to update a discord channel with the ct_config.json
"""
import discord
import subprocess
import shutil
import os
import io
from PIL import Image
from source.CT_Config import CT_Config
from source.Track import Track
from source.wszst import szs
from scripts.minimap import obj_to_png
bot = discord.Client()
SERVER_ID = 842865613918699590
TRACK_CHANNEL_ID = 871100630251499530
OLD_TRACK_CHANNEL_ID = 842867283428507699 # previous channel used by the program to get score
DATA_CHANNEL_ID = 871469647617216652
warning_level_message = [
"No special glitch",
"minor glitch",
"major glitch"
]
EMOTE_1STAR = 843109869107413012
EMOTE_2STAR = 843109881385058325
EMOTE_3STAR = 843109892330881107
placeholder_image_url = "https://media.discordapp.net/attachments/842865834090037310/875817942200238111/Placeholder.png"
get_norm_color_value = lambda x: int((x if x >= 0 else 0) if x <= 255 else 255)
get_R = lambda x: get_norm_color_value(-510 * x + 1021)
get_G = lambda x: get_norm_color_value(255 * x - 510)
get_B = lambda x: get_norm_color_value(254 * x - 127 if x < 1.5 else -254 * x + 890)
get_color_from_score = lambda x: (get_R(x), get_G(x), get_B(x))
def get_track_minimap(track: Track):
tmp_dir = f"./scripts/tmp/{track.sha1}/"
if not os.path.exists(tmp_dir): os.makedirs(tmp_dir)
szs.extract(track.file_szs, tmp_dir + "track.szs")
subprocess.run(["abmatt", "convert", tmp_dir + "track.szs.d/map_model.brres",
"to", tmp_dir + "map_model.obj"])
image = obj_to_png.render_top_view(obj_file=tmp_dir + "map_model.obj")
try: shutil.rmtree(tmp_dir)
except: print(f"can't remove tmp directory for {track.name}")
return image
@bot.event
async def on_ready():
guild: discord.Guild = bot.get_guild(id=SERVER_ID)
track_channel: discord.TextChannel = guild.get_channel(channel_id=TRACK_CHANNEL_ID)
old_track_channel: discord.TextChannel = guild.get_channel(channel_id=OLD_TRACK_CHANNEL_ID)
data_channel: discord.TextChannel = guild.get_channel(channel_id=DATA_CHANNEL_ID)
message_from_sha1 = {}
old_message_from_sha1 = {}
message: discord.Message
async for message in track_channel.history(limit=5000):
if message.author.id == bot.user.id:
for field in message.embeds[0].fields:
if "sha1" in field.name:
message_from_sha1[field.value] = message
async for message in old_track_channel.history(limit=5000):
if message.author.id == bot.user.id:
if "_" in message.content: continue
sha1 = message.content.split("ct.wiimm.de/i/")[-1].replace("|", "").strip()
old_message_from_sha1[sha1] = message
ct_config = CT_Config()
ct_config.load_ctconfig_file("./ct_config.json")
for track in ct_config.all_tracks:
try:
if track.name == "_": continue
if track.sha1 in message_from_sha1:
embed = message_from_sha1[track.sha1].embeds[0]
else:
embed = discord.Embed(title=f"**{track.get_track_name()}**",
description="", url=f"https://ct.wiimm.de/i/{track.sha1}")
for _ in range(6): embed.add_field(name="empty", value="empty")
author_link = ""
if "," not in track.author:
author_link = "http://wiki.tockdom.com/wiki/" + track.author.replace(" ", "_")
try: embed.set_author(name=track.author, url=author_link)
except: embed.set_author(name=track.author)
track_technical_data = szs.analyze(track.file_szs)
if hasattr(track, "score"):
scores = [track.score]
if track.sha1 in old_message_from_sha1:
for reaction in old_message_from_sha1[track.sha1].reactions:
if str(EMOTE_1STAR) in str(reaction.emoji): scores.extend([1] * (reaction.count - 1))
elif str(EMOTE_2STAR) in str(reaction.emoji): scores.extend([2] * (reaction.count - 1))
elif str(EMOTE_3STAR) in str(reaction.emoji): scores.extend([3] * (reaction.count - 1))
if track.sha1 in message_from_sha1:
for reaction in message_from_sha1[track.sha1].reactions:
if str(EMOTE_1STAR) in str(reaction.emoji): scores.extend([1] * (reaction.count - 1))
elif str(EMOTE_2STAR) in str(reaction.emoji): scores.extend([2] * (reaction.count - 1))
elif str(EMOTE_3STAR) in str(reaction.emoji): scores.extend([3] * (reaction.count - 1))
average_score = round(sum(scores) / len(scores), 2)
embed.colour = discord.Color.from_rgb(*get_color_from_score(average_score))
embed.set_field_at(index=0, name="Track Score", value=f"{average_score} (vote : {len(scores)})")
if hasattr(track, "warning"):
embed.set_field_at(index=1, name="Warning level", value=warning_level_message[track.warning])
if hasattr(track, "since_version"):
embed.set_field_at(index=2, name="Here since version", value=track.since_version)
embed.set_field_at(index=3, name="Lap count", value=track_technical_data["lap_count"])
embed.set_field_at(index=4, name="Speed multiplier", value=track_technical_data["speed_factor"])
embed.set_field_at(index=5, name="sha1", value=track.sha1)
if track.sha1 not in message_from_sha1:
with io.BytesIO() as image_binary:
track_img_path = f"./scripts/map preview/image/{track.get_track_name()}.png"
if os.path.exists(track_img_path):
image = Image.open(track_img_path)
image.save(image_binary, "PNG")
image_binary.seek(0)
message_map_preview = await data_channel.send(
file=discord.File(fp=image_binary, filename=f"map preview {track.sha1}.png"))
url_map_preview = message_map_preview.attachments[0].url
else: url_map_preview = placeholder_image_url
embed.set_image(url=url_map_preview)
with io.BytesIO() as image_binary:
image = get_track_minimap(track)
image.save(image_binary, "PNG")
image_binary.seek(0)
message_minimap = await data_channel.send(
file=discord.File(fp=image_binary, filename=f"minimap {track.sha1}.png"))
embed.set_thumbnail(url=message_minimap.attachments[0].url)
message = await track_channel.send(embed=embed)
await message.add_reaction(bot.get_emoji(EMOTE_1STAR))
await message.add_reaction(bot.get_emoji(EMOTE_2STAR))
await message.add_reaction(bot.get_emoji(EMOTE_3STAR))
await message.add_reaction("")
else:
message = message_from_sha1[track.sha1]
await message.edit(embed=embed)
except Exception as e:
print(f"error for track {track.name} : {str(e)}")
bot.run(os.environ['DISCORD_GR_TOKEN'])

View file

@ -0,0 +1,34 @@
"""
Note : use this script from the ../scripts/ directory
"""
import glob
import subprocess
import os
import shutil
from source.wszst import szs
from scripts import obj_to_png
def get_track_minimap(directory: str, sha1: str):
os.makedirs(tmp_dir := f"./scripts/tmp/{sha1}/", exist_ok=True)
szs.extract(f"{directory}{sha1}.szs", tmp_dir + "track.szs")
subprocess.run(["abmatt", "convert", tmp_dir + "track.szs.d/map_model.brres", "to", tmp_dir + "map_model.obj"])
try: img = obj_to_png.render_top_view(obj_file=tmp_dir + "map_model.obj")
except Exception as e:
print(e)
return None
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
return img
directory = "./file/Track/"
for track in glob.glob("*.szs", root_dir=directory):
sha1 = track.replace(".szs", "")
if (image := get_track_minimap(directory, sha1)) is not None:
image.save(f"./scripts/minimap/{sha1}.png")

View file

@ -1,10 +1,11 @@
"""
this script allow you to more easily select map preview for each track.
"""
import shutil
import requests
from selenium import webdriver
import keyboard
import shutil
import ctypes
import time
import glob
@ -13,40 +14,65 @@ import os
get_filename = lambda file: ".".join(file.split(".")[:-1])
get_nodir = lambda file: file.replace("\\", "/").split("/")[-1]
move_cursor_to = ctypes.windll.user32.SetCursorPos
os.makedirs("./map preview/tmp/", exist_ok=True)
chrome_option = webdriver.ChromeOptions()
driver = webdriver.Chrome("./map preview/chromedriver.exe", options=chrome_option)
driver.get("https://noclip.website/")
driver.fullscreen_window()
time.sleep(5)
driver.execute_script("var element = arguments[0]; element.parentNode.removeChild(element);",
driver.find_element_by_id("Panel"))
LAST_TRACK_PLAYED = "d97a4b29d422e830e07e98196e4f2e3f41a90086"
latest_track_passed = LAST_TRACK_PLAYED is None
tracks = glob.iglob("../file/Track/*.szs")
track = "none.png"
def ignore_track():
global track, driver
print("skipping to next track")
driver.close()
driver = webdriver.Chrome("./map preview/chromedriver.exe", options=chrome_option)
driver.get("https://noclip.website/")
skip_to_next()
def save_screenshot():
global track
print("saving screenshot")
driver.save_screenshot(filename=f"./map preview/image/{get_filename(get_nodir(track))}.png")
skip_to_next()
def skip_to_next():
global track
global track, latest_track_passed
if os.path.exists("./map preview/tmp/" + get_nodir(track)):
os.remove("./map preview/tmp/" + get_nodir(track))
track = next(tracks)
while os.path.exists(f"./map preview/image/{get_filename(get_nodir(track))}.png"):
while True:
sha1 = get_nodir(track).replace(".szs", "")
if not latest_track_passed and sha1 != LAST_TRACK_PLAYED:
track = next(tracks)
continue
else: latest_track_passed = True
if requests.get(f"https://github.com/Faraphel/MKWF-Install/raw/track-preview/map/{sha1}.png").status_code != 200: break
print(f"track {sha1} already exist !")
track = next(tracks)
shutil.copy(track, "./map preview/tmp/" + get_nodir(track))
print(track)
shutil.copy(track, f"./map preview/tmp/{get_nodir(track)}")
skip_to_next()
keyboard.add_hotkey('h', save_screenshot)
keyboard.add_hotkey('j', ignore_track)
while True:
time.sleep(1)

View file

@ -0,0 +1,41 @@
import bpy
import subprocess
import os
import glob
import shutil
TRACK_DIR: str = r"C:\Users\RC606\PycharmProjects\MKWF-Install\file\Track"
DEST_DIR: str = r"D:/gltf/"
def clear_scene():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
os.chdir(TRACK_DIR)
os.makedirs(DEST_DIR, exist_ok=True)
clear_scene()
for file in glob.iglob("./*.szs"):
try:
print(sha1 := file.split("/")[-1].split("\\")[-1].split(".")[0])
if os.path.exists(f"{DEST_DIR}/{sha1}.glb"): continue
subprocess.run(["wszst", "extract", file], creationflags=subprocess.CREATE_NO_WINDOW)
if not os.path.exists(f"./{sha1}.d/course_model.brres"): continue
subprocess.run(["abmatt", "convert", f"./{sha1}.d/course_model.brres", "to", f"./{sha1}.d/course_model.obj"], creationflags=subprocess.CREATE_NO_WINDOW)
if not os.path.exists(f"./{sha1}.d/course_model.obj"): continue
bpy.ops.import_scene.obj(filepath=f"./{sha1}.d/course_model.obj")
bpy.ops.export_scene.gltf(filepath=f"{DEST_DIR}/{sha1}.glb")
except Exception as e:
with open("./error.log", "a") as file: file.write(str(e))
finally:
try:
clear_scene()
shutil.rmtree(f"./{sha1}.d/")
except: pass

Binary file not shown.

View file

@ -1,6 +1,7 @@
discord.py
pygame
PyOpenGL
pywavefront
numpy
selenium
keyboard

View file

@ -1,10 +0,0 @@
import json
with open("../Pack/MKWFaraphel/ct_config.json", encoding="utf8", mode="r") as file:
ct_config = json.load(file)
get_key = lambda track: track["name"]
ct_config["tracks_list"].sort(key=get_key)
with open("../Pack/MKWFaraphel/ct_config.json", encoding="utf8", mode="w") as file:
json.dump(ct_config, file, ensure_ascii=False)

View file

@ -1,25 +0,0 @@
import discord, os
bot = discord.Client()
replace_list = {
"old_sha1": "new_sha1"
}
SERVER_ID = 842865613918699590
TRACK_CHANNEL_ID = 871100630251499530
@bot.event
async def on_ready():
server = bot.get_guild(SERVER_ID)
channel = server.get_channel(TRACK_CHANNEL_ID)
async for message in channel.history(limit=5000):
if message.author == bot.user:
embed = message.embeds[0]
org_sha1 = embed.fields[5].value
if org_sha1 in replace_list:
embed.set_field_at(5, name="sha1", value=replace_list[org_sha1])
await message.edit(embed=embed)
print(f"edited {org_sha1} to {replace_list[org_sha1]}")
print("finished !")
bot.run(os.environ['DISCORD_GR_TOKEN'])

View file

@ -1,50 +0,0 @@
import discord
import math
import json
import os
os.chdir("..")
bot = discord.Client()
SERVER_ID = 842865613918699590
TRACK_CHANNEL_ID = 871100630251499530
@bot.event
async def on_ready():
guild: discord.Guild = bot.get_guild(id=SERVER_ID)
track_channel: discord.TextChannel = guild.get_channel(channel_id=TRACK_CHANNEL_ID)
with open("./ct_config.json", "r", encoding="utf8") as f:
ct_config = json.load(f)
async for message in track_channel.history(limit=5000):
if message.author.id == bot.user.id:
raw_score = message.embeds[0].fields[0].value
sha1 = message.embeds[0].fields[5].value
score = float(raw_score.split(" ")[0])
if score % 1 >= 0.5: score = math.ceil(score)
else: score = math.floor(score)
for track in ct_config["tracks_list"]:
if track["sha1"] == sha1:
if track["score"] != score:
print(f"updated score of {track['name']} from {track['score']} to {score}")
track["score"] = score
break
else:
for cup in ct_config["cup"].values():
for track in cup["tracks"].values():
if "sha1" in track:
if track["sha1"] == sha1:
if track["name"] != "_":
if track["score"] != score:
print(f"updated score of {track['name']} from {track['score']} to {score}")
track["score"] = score
break
with open("./ct_config.json", "w", encoding="utf8") as f:
json.dump(ct_config, f, ensure_ascii=False)
print("end !")
bot.run(os.environ['DISCORD_GR_TOKEN'])

View file

@ -9,8 +9,8 @@ include_files = [
"./version",
"./translation.json",
"./assets",
"./tools",
"./source",
sys.exec_prefix + "\\DLLs\\tcl86t.dll",
sys.exec_prefix + "\\DLLs\\tk86t.dll",
@ -22,7 +22,6 @@ options = {
"includes": ["tkinter", "requests", "PIL", "distutils"],
"include_msvcr": True,
"packages": ["tkinter", "distutils"],
"excludes": ["source"],
}
}
@ -37,7 +36,7 @@ setup(
license='Apache-2.0',
author='Faraphel',
author_email='rc60650@hotmail.com',
description='Installateur pour Mario Kart Wii Faraphel.',
description='Mario Kart Wii Mod Installer.',
executables=[
Executable(
"./main.pyw",

View file

@ -444,6 +444,7 @@ class Game:
Prepare all files to install the mod (track, bmg text, descriptive image, ...)
"""
try:
os.makedirs(f"./file/", exist_ok=True)
os.makedirs(f"{self.common.ct_config.pack_path}/file/Track-WU8/", exist_ok=True)
max_step = (

View file

@ -1 +1,3 @@
from source.wszst import bmg, ctc, img, lec, wstrt, szs, wit
__all__ = ["bmg", "ctc", "img", "lec", "wstrt", "szs", "wit"]

View file

@ -2,6 +2,6 @@
"version": "0.11",
"subversion": "0",
"changelog": "see the changelog on MKWF's discord.",
"download_bin": "https://github.com/Faraphel/MKWF-Install/releases/download/0.11/MKWF.v0.11.zip",
"download_bin": "https://github.com/Faraphel/MKWF-Install/releases/download/0.11/MKWF.v0.11.Installer.only.zip",
"updater_bin": "https://github.com/Faraphel/MKWF-Install/raw/master/Updater/Updater.zip"
}