| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437 |
- /*
- * Copyright (C) 2022 The V-Gears Team
- *
- * This file is part of V-Gears
- *
- * V-Gears is free software: you can redistribute it and/or modify it under
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, version 3.0 (GPLv3) of the License.
- *
- * V-Gears is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- */
- #include <cctype>
- #include <boost/algorithm/string/predicate.hpp>
- #include <algorithm>
- #include <stdexcept>
- #include <unordered_set>
- #include "FieldCodeGenerator.h"
- #include "FieldDisassembler.h"
- #include "FieldEngine.h"
- const std::string FieldCodeGenerator::ON_UPDATE_FINISHED_CONDITION("self.on_update_finished");
- const std::string FieldCodeGenerator::ON_UPDATE_FINISHED_STATEMENT("self.on_update_finished = true");
- const std::string FunctionMetaData::DELIMITER("_");
- const std::string FunctionMetaData::START("start");
- const std::string FunctionMetaData::END("end");
- FunctionMetaData::FunctionMetaData(std::string meta_data){Parse(meta_data);}
- bool FunctionMetaData::IsStart() const{return start_;}
- bool FunctionMetaData::IsEnd() const{return end_;}
- std::string FunctionMetaData::GetEntityName(){return entity_name_;}
- int FunctionMetaData::GetCharacterId(){return character_id_;}
- void FunctionMetaData::Parse(std::string meta_data){
- std::deque<std::string> strs;
- boost::split(strs, meta_data, boost::is_any_of(DELIMITER), boost::token_compress_on);
- if (!strs.empty()){
- auto tmp = strs.front();
- strs.pop_front();
- ParseStart(tmp, strs);
- }
- }
- void FunctionMetaData::ParseStart(const std::string& item, std::deque<std::string>& strs){
- if (item == START){
- start_ = true;
- if (!strs.empty()){
- auto tmp = strs.front();
- strs.pop_front();
- ParseEnd(tmp, strs);
- }
- }
- else ParseEnd(item, strs);
- }
- void FunctionMetaData::ParseEnd(const std::string& item, std::deque<std::string>& strs){
- if (item == END){
- end_ = true;
- if (!strs.empty()){
- auto tmp = strs.front();
- strs.pop_front();
- ParseCharId(tmp, strs);
- }
- }
- else ParseCharId(item, strs);
- }
- void FunctionMetaData::ParseCharId(const std::string& item, std::deque<std::string>& strs){
- size_t parsed_length = 0;
- try{
- const int parsed_character_id = std::stoi(item, &parsed_length);
- if (parsed_length == item.size()){
- character_id_ = parsed_character_id;
- if (!strs.empty()){
- auto tmp = strs.front();
- strs.pop_front();
- ParseEntity(tmp, strs);
- }
- return;
- }
- }
- catch (const std::invalid_argument&){
- }
- catch (const std::out_of_range&){
- }
- ParseEntity(item, strs);
- }
- void FunctionMetaData::ParseEntity(const std::string& item, std::deque<std::string>& strs){
- entity_name_ = item;
- for (auto& part : strs) if (!part.empty()) entity_name_ += "_" + part;
- }
- void FieldCodeGenerator::Generate(InstVec& insts, const Graph& graph){
- // TODO: Break into parts
- auto instruction = insts.begin();
-
- std::vector<std::pair<Function&, InstVec>> functions_with_bodies;
- for (auto function = engine_->functions.begin(); function != engine_->functions.end(); ++ function){
- InstVec body;
- for (size_t i = 0; i < function->second.num_instructions; ++ i, ++ instruction)
- body.push_back(*instruction);
- functions_with_bodies.push_back(std::pair<Function&, InstVec> {function->second, body});
- }
- for (auto function = functions_with_bodies.begin(); function != functions_with_bodies.end(); ++ function){
- const size_t first_line_of_function = lines_.size();
- OnBeforeStartFunction(function->first);
- auto signature = ConstructFuncSignature(function->first);
- AddOutputLine(signature, false, true);
- OnStartFunction(function->first);
-
- // Generate labels for jump instruction targets.
- std::unordered_map<uint32, InstVec> labels;
- for (auto instruction = function->second.begin(); instruction != function->second.end(); ++ instruction){
- if ((*instruction)->IsCondJump() || (*instruction)->IsUncondJump()){
- auto targetAddr = (*instruction)->GetDestAddress();
- auto label = labels.find(targetAddr);
- if (label == labels.end()) labels.insert({targetAddr, InstVec()});
- labels[targetAddr].push_back(*instruction);
- }
- }
- // Lua can't jump into a block. If a jump from outside of the body of a conditional lands
- // in the middle of it, the conditional is written as a jump over its body instead of a
- // block, so the label ends up where every jump can see it.
- std::unordered_set<const Instruction*> flattened;
- for (auto cond = function->second.begin(); cond != function->second.end(); ++ cond){
- if (!(*cond)->IsCondJump()) continue;
- const uint32 start = (*cond)->GetAddress();
- const uint32 end = (*cond)->GetDestAddress();
- // The target has to be in the function to have a label.
- const bool target_in_function = std::any_of(
- function->second.begin(), function->second.end(),
- [end](const InstPtr& i){return i->GetAddress() == end;}
- );
- if (!target_in_function) continue;
- for (auto jump = function->second.begin(); jump != function->second.end(); ++ jump){
- if (!(*jump)->IsUncondJump()) continue;
- const uint32 destination = (*jump)->GetDestAddress();
- const uint32 origin = (*jump)->GetAddress();
- if (destination > start && destination < end && (origin < start || origin >= end)){
- flattened.insert(cond->get());
- break;
- }
- }
- }
- // Implemented instructions.
- // Some conditional jumps point to an address outside the function (i.e the starting
- // address of the next function) and the 'end' are not written to the Lua script. Keep
- // track of how many are needed and add them at the end of the function.
- int ends_needed = 0;
- for (auto instruction = function->second.begin(); instruction != function->second.end(); ++ instruction){
- auto label = labels.find((*instruction)->GetAddress());
- if (label != labels.end()){
- bool needs_label = false;
- bool needs_new_line = false;
- for (auto origin = label->second.begin(); origin != label->second.end(); ++ origin){
- if ((*origin)->IsCondJump() && flattened.count(origin->get()) == 0){
- ends_needed --;
- AddOutputLine("end", true, false);
- needs_new_line = true;
- }
- else needs_label = true;
- }
- if (needs_new_line) AddOutputLine("");
- if (needs_label) AddOutputLine((boost::format("::label_0x%1$X::") % label->first).str());
- }
- ValueStack stack;
- (*instruction)->ProcessInst(function->first, stack, engine_, this);
- //if (end_needed){
- // AddOutputLine("end -- end if", true, false);
- // end_needed = false;
- //}
- if ((*instruction)->IsCondJump() && flattened.count(instruction->get()) != 0){
- AddOutputLine((
- boost::format("if not (%s) then goto label_0x%X end")
- % stack.Pop()->GetString() % (*instruction)->GetDestAddress()
- ).str());
- }
- else if ((*instruction)->IsCondJump()){
- ends_needed ++;
- AddOutputLine((boost::format("if (%s) then") % stack.Pop()->GetString()).str(), false, true);
- // If the next instruction is the last in the function, mark the next pass to
- // add an 'end' after the instruction to close the if.
- //if ((*(instruction + 1))->GetAddress() == (*(function->second.back())).GetAddress())
- // end_needed = true;
- }
- else if ((*instruction)->IsUncondJump()){
- // If destination address is outside the functions, turn goto into a return.
- if ((*instruction)->GetDestAddress() > function->first.end_addr){
- AddOutputLine(
- "-- Overflowed jump to " + (boost::format("0x%1$X") % (*instruction)->GetDestAddress()).str()
- + " (last address in function is " + (boost::format("0x%1$X)") % function->first.end_addr).str()
- );
- if ("on_update" == function->first.name) AddOutputLine(ON_UPDATE_FINISHED_STATEMENT);
- AddOutputLine("do return 0 end");
- }
- // Prevent backward jumps in the on_start script.
- else if (
- "on_start" == function->first.name && (*instruction)->GetDestAddress() <= (*instruction)->GetAddress()
- ){
- AddOutputLine("-- No infinite loops in the on_start script.");
- AddOutputLine((boost::format("-- goto label_0x%1$X") % (*instruction)->GetDestAddress()).str());
- }
- else AddOutputLine((boost::format("goto label_0x%1$X") % (*instruction)->GetDestAddress()).str());
- }
- // Else, already output'd.
- }
- for(; ends_needed > 0; ends_needed --) AddOutputLine("end -- clean-up", true, false);
- // Add missing return:
- if ("return 0" != lines_.at(lines_.size() - 1).line && "do return 0 end" != lines_.at(lines_.size() - 1).line){
- if ("on_update" == function->first.name) AddOutputLine(ON_UPDATE_FINISHED_STATEMENT);
- // A function with no return goes on in the code of the next script.
- FunctionMetaData fall_meta(function->first.metadata);
- const std::string next = static_cast<FieldEngine*>(engine_)->GetFunctionFallThrough(
- fall_meta.GetEntityName(), function->first.name
- );
- if (!next.empty())
- AddOutputLine(
- "return EntityContainer[\"" + fall_meta.GetEntityName() + "\"]."
- + formatter_.GetFriendlyFunctionName(fall_meta.GetEntityName(), next) + "(self)"
- );
- else AddOutputLine("do return 0 end", false, false);
- }
- // A goto to a label that isn't in the function can't be compiled, and the whole script
- // would fail to load. It can't continue where it was told to, so it ends the script.
- {
- std::unordered_set<std::string> emitted_labels;
- for (size_t i = first_line_of_function; i < lines_.size(); ++ i)
- if (lines_[i].line.rfind("::label_0x", 0) == 0) emitted_labels.insert(lines_[i].line);
- for (size_t i = first_line_of_function; i < lines_.size(); ++ i){
- const std::string prefix = "goto label_0x";
- if (lines_[i].line.rfind(prefix, 0) != 0) continue;
- const std::string label = "::" + lines_[i].line.substr(5) + "::";
- if (emitted_labels.count(label) == 0)
- lines_[i].line = "do return 0 end -- was: " + lines_[i].line + " (not in this function)";
- }
- }
- OnEndFunction(function->first);
- }
- for (auto i = lines_.begin(); i != lines_.end(); ++i){
- if (i->unindent_before && indent_level_ > 0) indent_level_ --;
- output_ << IndentString(i->line) << std::endl;
- if (i->indent_after) indent_level_++;
- }
- }
- void FieldCodeGenerator::AddOutputLine(std::string line, bool unindent_before, bool indent_after){
- lines_.push_back(CodeLine(line, unindent_before, indent_after));
- }
- float FieldCodeGenerator::GetScaleFactor() const{return static_cast<FieldEngine*>(engine_)->GetScaleFactor();}
- // A name can be a field of a table written as "name = value" only if it is an identifier of Lua. The
- // entities of some fields have names such as "60f_1".
- static bool IsLuaIdentifier(const std::string& name){
- if (name.empty() || std::isdigit(static_cast<unsigned char>(name[0]))) return false;
- for (const char c : name)
- if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_') return false;
- return true;
- }
- void FieldCodeGenerator::OnBeforeStartFunction(const Function& function){
- FunctionMetaData meta_data(function.metadata);
- if (meta_data.IsStart()){
- AddOutputLine("EntityContainer[\"" + meta_data.GetEntityName() + "\"] = {", false, true);
- if (meta_data.GetCharacterId() != -1) AddOutputLine(meta_data.GetEntityName() + " = nil,\n");
- // Entities without a model (the Director and other helper scripts) still run the opcodes
- // that move or hide a model, and they do nothing. Give them an object that ignores them.
- else if (IsLuaIdentifier(meta_data.GetEntityName()))
- AddOutputLine(meta_data.GetEntityName() + " = NullEntity,\n");
- }
- const auto comment = formatter_.GetFunctionComment(meta_data.GetEntityName(), function.name);
- if (!comment.empty()) AddOutputLine("-- " + comment);
- }
- void FieldCodeGenerator::OnStartFunction(const Function& func){
- // Add some hacks for Director entity before the comments
- FunctionMetaData meta_data(func.metadata);
- if (meta_data.GetEntityName() == "Director" && func.name == "on_start"){
- // TODO: Don't hardcode Cloud, Use the one from the previous level,
- // The entity of Cloud is called "Cloud" in most fields, but not in all of them (md0 and
- // sinbil_1 call it "CLOUD", for example).
- std::string player_name = "Cloud";
- for (auto& other : static_cast<FieldEngine*>(engine_)->functions){
- FunctionMetaData other_meta(other.second.metadata);
- std::string lower = other_meta.GetEntityName();
- std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
- if (lower == "cloud"){
- player_name = other_meta.GetEntityName();
- break;
- }
- }
- AddOutputLine("-- HACK: Set default playable entity an ensure the camera follows it.");
- AddOutputLine("place_player_at_map_entry(\"" + player_name + "\")");
- AddOutputLine(
- "background2d:autoscroll_to_entity(entity_manager:get_entity(\"" + player_name + "\"))\n"
- );
- }
- // Don't run on_update again once it has reached its end.
- if (func.name == "on_update"){
- AddOutputLine("if " + ON_UPDATE_FINISHED_CONDITION + " then", false, true);
- AddOutputLine("return 0");
- AddOutputLine("end", true, false);
- }
- // For lines, exit if they are off.
- if (
- func.name == "on_approach" || func.name == "on_cross" || func.name == "on_near"
- || func.name == "on_near_once" || func.name == "on_leave"
- ){
- AddOutputLine("if self.on ~= nil and self.on == false then", false, true);
- AddOutputLine("return 0");
- AddOutputLine("end", true, false);
- }
- AddOutputLine("--[[");
- for (const auto& inst : insts_){
- if (inst->GetAddress() >= func.start_addr && inst->GetAddress() <= func.end_addr){
- std::stringstream output;
- output << inst;
- AddOutputLine(output.str());
- }
- }
- AddOutputLine("]]\n");
- }
- void FieldCodeGenerator::OnEndFunction(const Function& function){
- // End function.
- AddOutputLine("end,", true, false);
- // End class?
- FunctionMetaData meta_data(function.metadata);
- if (meta_data.IsEnd()){
- AddOutputLine("}\n", true, false);
- // The scripts of the entity that have the same code as other of its scripts.
- for (const auto& alias : static_cast<FieldEngine*>(engine_)->GetFunctionAliases()){
- if (alias.entity_name != meta_data.GetEntityName()) continue;
- const std::string container = "EntityContainer[\"" + alias.entity_name + "\"]";
- const std::string alias_name
- = formatter_.GetFriendlyFunctionName(alias.entity_name, alias.alias);
- const std::string target_name
- = formatter_.GetFriendlyFunctionName(alias.entity_name, alias.target);
- // The events of a line don't run while it is off, as in the functions of their own.
- if (
- alias.alias == "on_approach" || alias.alias == "on_cross" || alias.alias == "on_near"
- || alias.alias == "on_near_once" || alias.alias == "on_leave"
- ){
- AddOutputLine(
- container + "." + alias_name + " = function(self, ...)", false, true
- );
- AddOutputLine("if self.on ~= nil and self.on == false then", false, true);
- AddOutputLine("return 0");
- AddOutputLine("end", true, false);
- AddOutputLine("return " + container + "." + target_name + "(self, ...)");
- AddOutputLine("end", true, false);
- }
- else AddOutputLine(container + "." + alias_name + " = " + container + "." + target_name);
- }
- AddOutputLine("\n\n");
- }
- else AddOutputLine("\n");
- }
- std::string FieldCodeGenerator::ConstructFuncSignature(const Function &function){
- // Generate name
- FunctionMetaData meta_data(function.metadata);
- return formatter_.GetFriendlyFunctionName(meta_data.GetEntityName(), function.name) + " = function(self)";
- }
- bool FieldCodeGenerator::OutputOnlyRequiredLabels() const{return true;}
- FieldScriptFormatter& FieldCodeGenerator::GetFormatter(){return formatter_;}
- const int FieldCodeGenerator::DEFAULT_WINDOW_X = 16;
- const int FieldCodeGenerator::DEFAULT_WINDOW_Y = 176;
- const int FieldCodeGenerator::DEFAULT_WINDOW_WIDTH = 288;
- const int FieldCodeGenerator::DEFAULT_WINDOW_HEIGHT = 56;
- bool FieldCodeGenerator::IsWindowDefined(uint32 window_id) const{
- if (!defined_windows_collected_){
- for (const auto& inst : insts_){
- const uint32 opcode = inst->GetOpcode();
- if (opcode == OPCODES::WINDOW || opcode == OPCODES::WSIZW)
- defined_windows_.insert(inst->GetParam(0)->GetUnsigned());
- }
- defined_windows_collected_ = true;
- }
- return defined_windows_.find(window_id) != defined_windows_.end();
- }
- const std::string FieldCodeGenerator::FormatInstructionNotImplemented(
- const std::string& entity, uint32 address, uint32 opcode
- ){
- return (
- boost::format(
- "-- log:log(\"In entity \\\"%1%\\\", address 0x%2$08x: instruction 0x%3$04x not implemented\")"
- ) % entity % address % opcode
- ).str();
- }
- const std::string FieldCodeGenerator::FormatInstructionNotImplemented(
- const std::string& entity, uint32 address, const Instruction& instruction
- ){
- std::stringstream parameterList;
- //for (auto i = instruction._params.begin(); i != instruction._params.end(); ++ i){
- for (auto i = instruction.GetParams().begin(); i != instruction.GetParams().end(); ++ i){
- //if (i != instruction._params.begin()) parameterList << ", ";
- if (i != instruction.GetParams().begin()) parameterList << ", ";
- parameterList << *i;
- }
- return(
- boost::format(
- "-- log:log(\"In entity \\\"%1%\\\", address 0x%2$08x: instruction %3%(%4%) not implemented\")"
- ) % entity % address % instruction.GetName() % parameterList.str()
- ).str();
- }
- const std::string FieldCodeGenerator::FormatBool(uint32 value){return value == 0 ? "false" : "true";}
- const std::string FieldCodeGenerator::FormatInvertedBool(uint32 value){return value == 0 ? "true" : "false";}
|