26 # include <curl/curl.h>
27 # include <curl/easy.h>
31 #include "scriptany/scriptany.h"
32 #include "scriptarray/scriptarray.h"
33 #include "scripthelper/scripthelper.h"
34 #include "scriptmath/scriptmath.h"
35 #include "scriptstdstring/scriptstdstring.h"
67 #include <rapidjson/document.h>
68 #include <rapidjson/writer.h>
72 using namespace AngelScript;
86 void GameScript::logFormat(
const char*
format, ...)
88 char buffer[4000] = {};
89 sprintf(buffer,
"[RoR|Script] ");
90 char* buffer_pos = buffer + 13;
94 vsprintf(buffer_pos,
format, args);
100 void GameScript::activateAllVehicles()
105 void GameScript::setTrucksForcedAwake(
bool forceActive)
110 float GameScript::getTime()
115 void GameScript::setPersonPosition(
const Vector3& vec)
117 if (!this->HavePlayerAvatar(__FUNCTION__))
123 void GameScript::loadTerrain(
const String& terrain)
128 Vector3 GameScript::getPersonPosition()
130 Vector3 result(Vector3::ZERO);
136 void GameScript::movePerson(
const Vector3& vec)
138 if (!this->HavePlayerAvatar(__FUNCTION__))
144 void GameScript::setPersonRotation(
const Radian& rot)
146 if (!this->HavePlayerAvatar(__FUNCTION__))
152 Radian GameScript::getPersonRotation()
160 String GameScript::getCaelumTime()
172 void GameScript::setCaelumTime(
float value)
175 if (!this->HaveSimTerrain(__FUNCTION__))
182 bool GameScript::getCaelumAvailable()
192 void GameScript::stopTimer()
197 void GameScript::startTimer(
int id)
202 void GameScript::setTimeDiff(
float diff)
207 void GameScript::setBestLapTime(
float time)
212 void GameScript::setWaterHeight(
float value)
214 if (!this->HaveSimTerrain(__FUNCTION__))
225 float GameScript::getGroundHeight(Vector3& v)
227 float result = -1.0f;
233 float GameScript::getWaterHeight()
246 float GameScript::getGravity()
256 void GameScript::setGravity(
float value)
258 if (!this->HaveSimTerrain(__FUNCTION__))
269 int GameScript::getNumTrucksByFlag(
int flag)
274 if (!flag ||
static_cast<int>(actor->ar_state) == flag)
280 int GameScript::getCurrentTruckNumber()
286 void GameScript::registerForEvent(
int eventValue)
298 void GameScript::unRegisterEvent(
int eventValue)
324 void GameScript::flashMessage(String& txt,
float time,
float charHeight)
329 void GameScript::message(String& txt, String& icon)
334 void GameScript::updateDirectionArrow(String& text, Vector3& vec)
339 int GameScript::getChatFontSize()
344 void GameScript::setChatFontSize(
int size)
349 void GameScript::showChooser(
const String& type,
const String&
instance,
const String& box)
353 if (type ==
"airplane")
361 if (type ==
"extension")
367 if (type ==
"trailer")
373 if (type ==
"vehicle")
383 void GameScript::repairVehicle(
const String&
instance,
const String& box,
bool keepPosition)
388 void GameScript::removeVehicle(
const String& event_source_instance_name,
const String& event_source_box_name)
397 AngelScript::CScriptArray* GameScript::getEditorObjects()
399 if (!this->HaveSimTerrain(__FUNCTION__))
406 std::string arraydecl =
fmt::format(
"array<{}>",
"TerrainEditorObjectClass@");
410 for (AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
414 arr->SetValue(i, &ref);
421 void GameScript::destroyObject(
const String& instanceName)
423 if (!this->HaveSimTerrain(__FUNCTION__))
432 void GameScript::moveObjectVisuals(
const String& instanceName,
const Vector3& pos)
434 if (!this->HaveSimTerrain(__FUNCTION__))
443 void GameScript::spawnObject(
const String& objectName,
const String& instanceName,
const Vector3& pos,
const Vector3& rot,
const String& eventhandler,
bool uniquifyMaterials)
445 if (!this->HaveSimTerrain(__FUNCTION__))
450 this->logFormat(
"spawnObject(): Cannot spawn object, no terrain loaded!");
456 this->logFormat(
"spawnObject(): Cannot spawn object, no terrain script loaded!");
463 if (module ==
nullptr)
465 this->logFormat(
"spawnObject(): Failed to fetch/create script module");
469 int handler_func_id = -1;
470 if (!eventhandler.empty())
475 "spawnObject(): Specifying event handler function in `game.spawnObject()` (or .TOBJ file) is obsolete and only works with terrain scripts;"
476 " Use `eventCallbackEx()` with event `SE_EVENTBOX_ENTER` instead, it does the same job and works with any script."
477 " Just pass an empty string to the `game.spawnObject()` parameter.");
484 if (handler_func !=
nullptr)
486 handler_func_id = handler_func->GetId();
490 const String type =
"";
500 void GameScript::hideDirectionArrow()
505 bool GameScript::getScreenPosFromWorldPos(Ogre::Vector3
const& world_pos, Ogre::Vector2& out_screen)
507 ImVec2 screen_size = ImGui::GetIO().DisplaySize;
510 Ogre::Vector3 pos_xyz = world2screen.
Convert(world_pos);
513 out_screen.x = pos_xyz.x;
514 out_screen.y = pos_xyz.y;
520 Ogre::Vector2 GameScript::getDisplaySize()
522 ImVec2 size = ImGui::GetIO().DisplaySize;
523 return Vector2(size.x, size.y);
526 Ogre::Vector2 GameScript::getMouseScreenPosition()
528 ImVec2 pos = ImGui::GetIO().MousePos;
529 return Vector2(pos.x, pos.y);
532 int GameScript::setMaterialAmbient(
const String& materialName,
float red,
float green,
float blue)
536 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
539 m->setAmbient(red, green, blue);
549 int GameScript::setMaterialDiffuse(
const String& materialName,
float red,
float green,
float blue,
float alpha)
553 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
556 m->setDiffuse(red, green, blue, alpha);
566 int GameScript::setMaterialSpecular(
const String& materialName,
float red,
float green,
float blue,
float alpha)
570 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
573 m->setSpecular(red, green, blue, alpha);
583 int GameScript::setMaterialEmissive(
const String& materialName,
float red,
float green,
float blue)
587 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
590 m->setSelfIllumination(red, green, blue);
600 int GameScript::getTextureUnitState(TextureUnitState** tu,
const String materialName,
int techniqueNum,
int passNum,
int textureUnitNum)
605 MaterialPtr m = MaterialManager::getSingleton().getByName(materialName);
610 if (techniqueNum < 0 || techniqueNum > m->getNumTechniques())
612 Technique* t = m->getTechnique(techniqueNum);
617 if (passNum < 0 || passNum > t->getNumPasses())
619 Pass* p = t->getPass(passNum);
624 if (textureUnitNum < 0 || textureUnitNum > p->getNumTextureUnitStates())
626 TextureUnitState* tut = p->getTextureUnitState(textureUnitNum);
634 int GameScript::setMaterialTextureName(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
const String& textureName)
638 TextureUnitState* tu = 0;
639 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
640 if (res == 0 && tu != 0)
643 tu->setTextureName(textureName);
654 int GameScript::setMaterialTextureRotate(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
float rotation)
658 TextureUnitState* tu = 0;
659 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
660 if (res == 0 && tu != 0)
662 tu->setTextureRotate(Degree(rotation));
673 int GameScript::setMaterialTextureScroll(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
float sx,
float sy)
677 TextureUnitState* tu = 0;
678 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
679 if (res == 0 && tu != 0)
681 tu->setTextureScroll(sx, sy);
692 int GameScript::setMaterialTextureScale(
const String& materialName,
int techniqueNum,
int passNum,
int textureUnitNum,
float u,
float v)
696 TextureUnitState* tu = 0;
697 int res = getTextureUnitState(&tu, materialName, techniqueNum, passNum, textureUnitNum);
698 if (res == 0 && tu != 0)
700 tu->setTextureScale(u, v);
711 float GameScript::rangeRandom(
float from,
float to)
713 return Math::RangeRandom(from, to);
716 int GameScript::getLoadedTerrain(String& result)
718 String terrainName =
"";
723 result = terrainName;
726 return !terrainName.empty();
734 void GameScript::clearEventCache()
736 if (!this->HaveSimTerrain(__FUNCTION__))
741 this->logFormat(
"Cannot execute '%s', collisions not ready", __FUNCTION__);
748 void GameScript::setCameraPosition(
const Vector3& pos)
750 if (!this->HaveMainCamera(__FUNCTION__))
756 void GameScript::setCameraDirection(
const Vector3& rot)
758 if (!this->HaveMainCamera(__FUNCTION__))
764 void GameScript::setCameraOrientation(
const Quaternion& q)
766 if (!this->HaveMainCamera(__FUNCTION__))
772 void GameScript::setCameraYaw(
float rotX)
774 if (!this->HaveMainCamera(__FUNCTION__))
780 void GameScript::setCameraPitch(
float rotY)
782 if (!this->HaveMainCamera(__FUNCTION__))
788 void GameScript::setCameraRoll(
float rotZ)
790 if (!this->HaveMainCamera(__FUNCTION__))
796 Vector3 GameScript::getCameraPosition()
798 Vector3 result(Vector3::ZERO);
804 Vector3 GameScript::getCameraDirection()
806 Vector3 result(Vector3::ZERO);
815 Quaternion GameScript::getCameraOrientation()
817 Quaternion result(Quaternion::ZERO);
823 void GameScript::cameraLookAt(
const Vector3& pos)
825 if (!this->HaveMainCamera(__FUNCTION__))
831 int GameScript::useOnlineAPI(
const String& apiquery,
const AngelScript::CScriptDictionary& dict, String& result)
842 if (player_actor ==
nullptr)
848 std::string token = std::string(
"RoR-Api-User-Token: ") + hashtok;
855 rapidjson::Document j_doc;
858 j_doc.AddMember(
"user-name", rapidjson::StringRef(
App::mp_player_name->getStr().c_str()), j_doc.GetAllocator());
859 j_doc.AddMember(
"user-country", rapidjson::StringRef(
App::app_country->getStr().c_str()), j_doc.GetAllocator());
860 j_doc.AddMember(
"user-token", rapidjson::StringRef(hashtok.c_str()), j_doc.GetAllocator());
862 j_doc.AddMember(
"terrain-name", rapidjson::StringRef(terrain_name.c_str()), j_doc.GetAllocator());
863 j_doc.AddMember(
"terrain-filename", rapidjson::StringRef(
App::sim_terrain_name->getStr().c_str()), j_doc.GetAllocator());
865 j_doc.AddMember(
"script-name", rapidjson::StringRef(script_name.c_str()), j_doc.GetAllocator());
866 j_doc.AddMember(
"script-hash", rapidjson::StringRef(script_hash.c_str()), j_doc.GetAllocator());
868 j_doc.AddMember(
"actor-name", rapidjson::StringRef(player_actor->
ar_design_name.c_str()), j_doc.GetAllocator());
869 j_doc.AddMember(
"actor-filename", rapidjson::StringRef(player_actor->
ar_filename.c_str()), j_doc.GetAllocator());
870 j_doc.AddMember(
"actor-hash", rapidjson::StringRef(player_actor->
ar_filehash.c_str()), j_doc.GetAllocator());
872 rapidjson::Value j_linked_actors(rapidjson::kArrayType);
875 rapidjson::Value j_actor(rapidjson::kObjectType);
876 j_actor.AddMember(
"actor-name", rapidjson::StringRef(actor->
ar_design_name.c_str()), j_doc.GetAllocator());
877 j_actor.AddMember(
"actor-filename", rapidjson::StringRef(actor->
ar_filename.c_str()), j_doc.GetAllocator());
878 j_actor.AddMember(
"actor-hash", rapidjson::StringRef(actor->
ar_filehash.c_str()), j_doc.GetAllocator());
879 j_linked_actors.PushBack(j_actor, j_doc.GetAllocator());
881 j_doc.AddMember(
"linked-actors", j_linked_actors, j_doc.GetAllocator());
883 j_doc.AddMember(
"avg-fps", getAvgFPS(), j_doc.GetAllocator());
884 j_doc.AddMember(
"ror-version", rapidjson::StringRef(
ROR_VERSION_STRING), j_doc.GetAllocator());
886 for (
auto item : dict)
888 const std::string& key = item.GetKey();
889 const std::string* value = (std::string *)item.GetAddressOfValue();
890 j_doc.AddMember(rapidjson::StringRef(key.c_str()), rapidjson::StringRef(value->c_str()), j_doc.GetAllocator());
893 rapidjson::StringBuffer buffer;
894 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
895 j_doc.Accept(writer);
896 std::string json = buffer.GetString();
900 _L(
"using Online API..."),
"information.png");
902 LOG(
"[RoR|GameScript] Submitting race results to '" + url +
"'");
904 std::thread([url, user, token, json]()
906 long response_code = 0;
908 struct curl_slist *slist = NULL;
909 slist = curl_slist_append(slist,
"Accept: application/json");
910 slist = curl_slist_append(slist,
"Content-Type: application/json");
911 slist = curl_slist_append(slist, user.c_str());
912 slist = curl_slist_append(slist, token.c_str());
914 CURL *curl = curl_easy_init();
915 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
916 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
917 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
919 CURLcode curl_result = curl_easy_perform(curl);
920 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
922 if (curl_result != CURLE_OK || response_code != 200)
924 Ogre::LogManager::getSingleton().stream()
925 <<
"[RoR|GameScript] `useOnlineAPI()` failed to submit data;"
926 <<
" Error: '" << curl_easy_strerror(curl_result) <<
"'; HTTP status code: " << response_code;
929 curl_easy_cleanup(curl);
931 curl_slist_free_all(slist);
936 _L(
"Cannot use Online API in this build (CURL not available)"));
942 void GameScript::openUrlInDefaultBrowser(
const std::string& url)
947 void GameScript::fetchUrlAsStringAsync(
const std::string& url,
const std::string& display_filename)
949 #if defined(USE_CURL)
959 std::thread(std::move(pktask), task).detach();
960 #endif // defined(USE_CURL)
963 void GameScript::boostCurrentTruck(
float factor)
969 rpm += 2000.0f * factor;
1004 int GameScript::getScriptVariable(
const Ogre::String& varName,
void *ref,
int refTypeId,
ScriptUnitID_t nid)
1009 int GameScript::sendGameCmd(
const String& message)
1017 #endif // USE_SOCKETW
1022 AngelScript::CScriptArray* GameScript::getRunningScripts()
1024 std::vector<ScriptUnitID_t> ids;
1026 ids.push_back(pair.first);
1038 AngelScript::CScriptDictionary* dict = AngelScript::CScriptDictionary::Create(
App::GetScriptEngine()->getEngine());
1042 dict->Set(
"uniqueId", (asINT64)info.
uniqueId);
1043 dict->Set(
"scriptName",
new std::string(info.
scriptName), stringTypeid);
1044 dict->Set(
"scriptCategory", &info.
scriptCategory, scriptCategoryTypeid);
1045 dict->Set(
"eventMask", (asINT64)info.
eventMask);
1046 dict->Set(
"scriptBuffer",
new std::string(info.
scriptBuffer), stringTypeid);
1074 if (actor !=
nullptr)
1081 ActorPtr GameScript::spawnTruck(Ogre::String& truckName, Ogre::Vector3& pos, Ogre::Vector3& rot)
1085 rq.
asr_rotation = Quaternion(Degree(rot.x), Vector3::UNIT_X) * Quaternion(Degree(rot.y), Vector3::UNIT_Y) * Quaternion(Degree(rot.z), Vector3::UNIT_Z);
1090 ActorPtr GameScript::spawnTruckAI(Ogre::String& truckName, Ogre::Vector3& pos, Ogre::String& truckSectionConfig, std::string& truckSkin,
int x)
1098 std::vector<Ogre::Vector3> waypoints;
1105 std::reverse(waypoints.begin(), waypoints.end());
1109 Ogre::Vector3 dir = Ogre::Vector3::ZERO;
1110 if (waypoints.size() >= 2)
1111 dir = waypoints[0] - waypoints[1];
1112 else if (waypoints.size() >= 1)
1115 rq.
asr_rotation = Ogre::Vector3::UNIT_X.getRotationTo(dir, Ogre::Vector3::UNIT_Y);
1130 AngelScript::CScriptArray* GameScript::getWaypoints(
int x)
1132 std::vector<Ogre::Vector3> vec;
1139 std::reverse(vec.begin(), vec.end());
1142 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(AngelScript::asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(
"array<vector3>"), vec.size());
1144 for(AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
1147 arr->SetValue(i, &vec[i]);
1153 AngelScript::CScriptArray* GameScript::getAllTrucks()
1156 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(AngelScript::asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(
"array<BeamClass@>"), actors.size());
1158 for (AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
1161 arr->SetValue(i, &actors[i]);
1167 void GameScript::addWaypoint(
const Ogre::Vector3& pos)
1169 std::vector<Ogre::Vector3> waypoints;
1176 AngelScript::CScriptArray* GameScript::getWaypointsSpeed()
1178 std::vector<int> vec;
1184 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(AngelScript::asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(
"array<int>"), vec.size());
1186 for(AngelScript::asUINT i = 0; i < arr->GetSize(); i++)
1189 arr->SetValue(i, &vec[i]);
1195 int GameScript::getAIVehicleCount()
1201 int GameScript::getAIVehicleDistance()
1207 int GameScript::getAIVehiclePositionScheme()
1213 int GameScript::getAIVehicleSpeed()
1219 Ogre::String GameScript::getAIVehicleName(
int x)
1233 Ogre::String GameScript::getAIVehicleSectionConfig(
int x)
1247 std::string GameScript::getAIVehicleSkin(
int x)
1261 int GameScript::getAIRepeatTimes()
1267 int GameScript::getAIMode()
1275 void GameScript::setAIVehicleCount(
int num)
1280 void GameScript::setAIVehicleDistance(
int dist)
1285 void GameScript::setAIVehiclePositionScheme(
int scheme)
1290 void GameScript::setAIVehicleSpeed(
int speed)
1295 void GameScript::setAIVehicleName(
int x, std::string name)
1307 void GameScript::setAIVehicleSectionConfig(
int x, std::string config)
1318 this->
log(
fmt::format(
"setAIVehicleSectionConfig: ERROR, valid 'x' is 0 or 1, got {}", x));
1323 void GameScript::setAIVehicleSkin(
int x, std::string skin)
1334 this->
log(
fmt::format(
"setAIVehicleSkin: ERROR, valid 'x' is 0 or 1, got {}", x));
1339 void GameScript::setAIRepeatTimes(
int times)
1344 void GameScript::setAIMode(
int mode)
1349 void GameScript::showMessageBox(Ogre::String& title, Ogre::String& text,
bool use_btn1, Ogre::String& btn1_text,
bool allow_close,
bool use_btn2, Ogre::String& btn2_text)
1352 const char* btn1_cstr =
nullptr;
1353 const char* btn2_cstr =
nullptr;
1357 btn1_cstr = (btn1_text.empty() ?
"~1~" : btn1_text.c_str());
1361 btn2_cstr = (btn2_text.empty() ?
"~2~" : btn2_text.c_str());
1367 void GameScript::backToMenu()
1373 void GameScript::quitGame()
1378 float GameScript::getFPS()
1383 float GameScript::getAvgFPS()
1388 bool GameScript::getMousePositionOnTerrain(Ogre::Vector3& out_pos)
1390 if (!HaveSimTerrain(__FUNCTION__))
1398 out_pos = ray_result.position;
1400 return ray_result.hit;
1411 results_array.push_back(obj);
1415 bool queryResult(SceneQuery::WorldFragment* fragment, Real distance)
override
1421 CScriptArray* GameScript::getMousePointedMovableObjects()
1423 if (!HaveSimTerrain(__FUNCTION__))
1430 query.setSortByDistance(
true);
1433 query.execute(&qlis);
1437 Ogre::SceneManager* GameScript::getSceneManager()
1442 bool GameScript::pushMessage(
MsgType type, AngelScript::CScriptDictionary* dict)
1487 if (!has_filename && !has_buffer)
1489 this->
log(
fmt::format(
"{}: ERROR, either 'filename' or 'buffer' must be set!", log_msg));
1496 int64_t instance_id;
1499 this->
log(
fmt::format(
"{}: WARNING, category 'ACTOR' specified but 'associated_actor' not given.", log_msg, rq->
lsr_filename));
1576 std::string skin_name;
1581 this->
log(
fmt::format(
"{}: WARNING, skin '{}' is not installed.", log_msg, skin_name));
1598 int64_t instance_id = -1;
1619 int64_t instance_id = -1;
1629 this->
log(
fmt::format(
"{}: Actor with instance ID '{}' not found!", log_msg, instance_id));
1643 int64_t instance_id = -1;
1646 && instance_id > -1)
1656 Ogre::Vector3 position;
1659 m.
payload =
new Ogre::Vector3(position);
1681 case (int64_t)FreeForceType::CONSTANT:
1693 case (int64_t)FreeForceType::TOWARDS_COORDS:
1705 case (int64_t)FreeForceType::TOWARDS_NODE:
1800 CScriptArray* GameScript::getAllSoundScriptTemplates()
1810 AngelScript::CScriptArray* GameScript::getAllSoundScriptInstances()
1815 SoundPtr GameScript::createSoundFromResource(
const std::string& filename,
const std::string& resource_group_name)
1820 SoundScriptInstancePtr GameScript::createSoundScriptInstance(
const std::string& template_name,
int actor_instance_id = SoundScriptInstance::ACTOR_ID_UNKNOWN)
1825 bool GameScript::checkResourceExists(
const std::string& filename,
const std::string& resource_group)
1829 std::string resource_name = this->CheckFileAccess(
"checkResourceExists()", filename, resource_group);
1830 if (resource_name ==
"")
1834 return Ogre::ResourceGroupManager::getSingleton().resourceExists(resource_group, resource_name);
1843 bool GameScript::deleteResource(
const std::string& filename,
const std::string& resource_group)
1847 std::string resource_name = this->CheckFileAccess(
"deleteResource()", filename, resource_group);
1848 if (resource_name ==
"")
1852 Ogre::ResourceGroupManager::getSingleton().deleteResource(resource_name, resource_group);
1862 std::string GameScript::loadTextResourceAsString(
const std::string& filename,
const std::string& resource_group)
1866 std::string resource_name = this->CheckFileAccess(
"loadTextResourceAsString()", filename, resource_group);
1867 if (resource_name ==
"")
1870 Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(resource_name, resource_group);
1872 if (stream.isNull() || !stream->isReadable())
1875 fmt::format(
"loadTextResourceAsString() could not read resource '{}' in group '{}'",
1876 resource_name, resource_group));
1880 #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
1885 const size_t BUF_LEN = 4000;
1886 char buf[BUF_LEN] = {};
1890 size_t read_len = stream->read(buf, BUF_LEN);
1891 if (read_len < BUF_LEN)
1896 str.append(buf, read_len);
1900 return stream->getAsString();
1910 bool GameScript::createTextResourceFromString(
const std::string& data,
const std::string& filename,
const std::string& resource_group,
bool overwrite)
1914 std::string resource_name = this->CheckFileAccess(
"createTextResourceFromString()", filename, resource_group);
1915 if (resource_name ==
"")
1918 Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().createResource(resource_name, resource_group, overwrite);
1920 if (stream.isNull() || !stream->isWriteable())
1923 fmt::format(
"createTextResourceFromString() could not create resource '{}' in group '{}'",
1924 resource_name, resource_group));
1928 stream->write(data.data(), data.size());
1938 AngelScript::CScriptArray* GameScript::findResourceFileInfo(
const std::string& resource_group,
const std::string& pattern,
bool dirs )
1943 Ogre::FileInfoListPtr fileInfoList
1944 = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(resource_group, pattern, dirs);
1948 AngelScript::CScriptArray* arr = AngelScript::CScriptArray::Create(typeinfo);
1950 for (
const Ogre::FileInfo& fileinfo: *fileInfoList)
1952 AngelScript::CScriptDictionary* dict = AngelScript::CScriptDictionary::Create(
App::GetScriptEngine()->getEngine());
1953 dict->Set(
"filename",
new std::string(fileinfo.filename), stringTypeid);
1954 dict->Set(
"basename",
new std::string(fileinfo.basename), stringTypeid);
1955 dict->Set(
"compressedSize", (asINT64)fileinfo.compressedSize);
1956 dict->Set(
"uncompressedSize", (asINT64)fileinfo.uncompressedSize);
1958 arr->InsertLast(dict);
1969 Ogre::Image GameScript::loadImageResource(
const std::string& filename,
const std::string& resource_group)
1973 std::string resource_name = this->CheckFileAccess(
"loadImageResource()", filename, resource_group);
1974 if (resource_name ==
"")
1975 return Ogre::Image();
1978 return img.load(resource_name, resource_group);
1983 return Ogre::Image();
1987 bool GameScript::serializeMeshResource(
const std::string& filename,
const std::string& resource_group,
const Ogre::MeshPtr& mesh)
1991 std::string resource_name = this->CheckFileAccess(
"serializeMeshResource()", filename, resource_group);
1992 if (resource_name ==
"")
1995 Ogre::MeshSerializer ser;
1996 Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().createResource(resource_name, resource_group);
1997 ser.exportMesh(mesh.get(), stream);
2010 bool GameScript::HaveSimTerrain(
const char* func_name)
2014 this->logFormat(
"Cannot execute '%s', terrain not ready", func_name);
2020 bool GameScript::HavePlayerAvatar(
const char* func_name)
2024 this->logFormat(
"Cannot execute '%s', player avatar not ready", func_name);
2030 bool GameScript::HaveMainCamera(
const char* func_name)
2034 this->logFormat(
"Cannot execute '%s', main camera not ready", func_name);
2040 std::string GameScript::CheckFileAccess(
const char* func_name,
const std::string& filename,
const std::string& resource_group)
2045 std::string basename, extension, path;
2046 Ogre::StringUtil::splitFullFilename(filename, basename, extension, path);
2050 fmt::format(
"{}: access denied to '{}' with group '{}' - file paths are not allowed",
2051 func_name, filename, resource_group));
2056 return basename +
"." + extension;