示例#1
0
void Session::processSignIn(const QString &data) {

    try {
        switch (m_sessionState) {
            case SessionClosed:
                break;

            case SigningIn: {
                QScriptValue processSignIn = m_scriptObject.property("processSignIn");
                QScriptValueList args;
                args.append(data.trimmed());
                processSignIn.call(m_scriptObject, args);
                break;
            }

            case SignedIn: {
                CommandEvent event(m_player, data);
                event.process();
                break;
            }
        }

        ScriptEngine *engine = ScriptEngine::instance();
        if (engine->hasUncaughtException()) {
            LogUtil::logException("Script Exception: %1\n"
                                  "In Session::processSignIn()", engine->uncaughtException());
        }
    } catch (GameException &exception) {
        LogUtil::logError("Exception in Session::processSignIn(): %1", exception.what());
    }
}
示例#2
0
文件: Game.cpp 项目: BlackLotus/gemrb
Map *Game::GetMap(const char *areaname, bool change)
{
	int index = LoadMap(areaname, change);
	if (index >= 0) {
		if (change) {
			MapIndex = index;
			area = GetMap(index);
			memcpy (CurrentArea, areaname, 8);
			area->SetupAmbients();
			//change the tileset if needed
			area->ChangeMap(IsDay());
			ChangeSong(false, true);
			Infravision();

			//call area customization script for PST
			//moved here because the current area is set here
			ScriptEngine *sE = core->GetGUIScriptEngine();
			if (core->HasFeature(GF_AREA_OVERRIDE) && sE) {
				//area ResRef is accessible by GemRB.GetGameString (STR_AREANAME)
				sE->RunFunction("Maze", "CustomizeArea");
			}

			return area;
		}
		return GetMap(index);
	}
	return NULL;
}
示例#3
0
double
Feature::eval( NumericExpression& expr, FilterContext const* context ) const
{
    const NumericExpression::Variables& vars = expr.variables();
    for( NumericExpression::Variables::const_iterator i = vars.begin(); i != vars.end(); ++i )
    {
      double val = 0.0;
      AttributeTable::const_iterator ai = _attrs.find(toLower(i->first));
      if (ai != _attrs.end())
      {
        val = ai->second.getDouble(0.0);
      }
      else if (context)
      {
        //No attr found, look for script
        ScriptEngine* engine = context->getSession()->getScriptEngine();
        if (engine)
        {
          ScriptResult result = engine->run(i->first, this, context);
          if (result.success())
            val = result.asDouble();
          else {
              OE_WARN << LC << "Feature Script error on '" << expr.expr() << "': " << result.message() << std::endl;
          }
        }
      }

      expr.set( *i, val); //osgEarth::as<double>(getAttr(i->first),0.0) );
    }

    return expr.eval();
}
示例#4
0
QScriptValue ScriptEngine::js_loadFile(QScriptContext *context, QScriptEngine *qtengine)
{
    ScriptEngine *engine = static_cast<ScriptEngine *>(qtengine);
    if (context->argumentCount() < 1) {
        return context->throwError(
                    ScriptEngine::tr("The loadFile function requires a file path."));
    }

    if (engine->m_currentDirPathStack.isEmpty()) {
        return context->throwError(
            ScriptEngine::tr("loadFile: internal error. No current directory."));
    }

    QScriptValue result;
    const QString relativeFilePath = context->argument(0).toVariant().toString();
    try {
        const QString filePath = FileInfo::resolvePath(engine->m_currentDirPathStack.top(),
                                                       relativeFilePath);
        result = engine->importFile(filePath, QScriptValue());
    } catch (const ErrorInfo &e) {
        result = context->throwError(e.toString());
    }

    return result;
}
示例#5
0
const std::string&
Feature::eval( StringExpression& expr, FilterContext const* context ) const
{
    const StringExpression::Variables& vars = expr.variables();
    for( StringExpression::Variables::const_iterator i = vars.begin(); i != vars.end(); ++i )
    {
      std::string val = "";
      AttributeTable::const_iterator ai = _attrs.find(toLower(i->first));
      if (ai != _attrs.end())
      {
        val = ai->second.getString();
      }
      else if (context)
      {
        //No attr found, look for script
        ScriptEngine* engine = context->getSession()->getScriptEngine();
        if (engine)
        {
          ScriptResult result = engine->run(i->first, this, context);
          if (result.success())
            val = result.asString();
          else
            OE_WARN << LC << "Feature Script error on '" << expr.expr() << "': " << result.message() << std::endl;
        }
      }

      expr.set( *i, val );
    }

    return expr.eval();
}
示例#6
0
bool Sword25Engine::appMain() {
	// The main script start. This script loads all the other scripts and starts the actual game.
	ScriptEngine *scriptPtr = Kernel::getInstance()->getScript();
	assert(scriptPtr);
	scriptPtr->executeFile(DEFAULT_SCRIPT_FILE);

	return true;
}
示例#7
0
文件: Game.cpp 项目: dhewg/gemrb
/* Loads an area */
int Game::LoadMap(const char* ResRef, bool loadscreen)
{
	unsigned int i;
	Map *newMap;
	PluginHolder<MapMgr> mM(IE_ARE_CLASS_ID);
	ScriptEngine *sE = core->GetGUIScriptEngine();

	//this shouldn't happen
	if (!mM) {
		return -1;
	}

	int index = FindMap(ResRef);
	if (index>=0) {
		return index;
	}

	bool hide = false;
	if (loadscreen && sE) {
		hide = core->HideGCWindow();
		sE->RunFunction("LoadScreen", "StartLoadScreen");
		sE->RunFunction("LoadScreen", "SetLoadScreen");
	}
	DataStream* ds = gamedata->GetResource( ResRef, IE_ARE_CLASS_ID );
	if (!ds) {
		goto failedload;
	}
	if(!mM->Open(ds)) {
		goto failedload;
	}
	newMap = mM->GetMap(ResRef, IsDay());
	if (!newMap) {
		goto failedload;
	}

	core->LoadProgress(100);

	for (i = 0; i < PCs.size(); i++) {
		if (stricmp( PCs[i]->Area, ResRef ) == 0) {
			newMap->AddActor( PCs[i] );
		}
	}
	for (i = 0; i < NPCs.size(); i++) {
		if (stricmp( NPCs[i]->Area, ResRef ) == 0) {
			newMap->AddActor( NPCs[i] );
		}
	}
	if (hide) {
		core->UnhideGCWindow();
	}
	return AddMap( newMap );
failedload:
	if (hide) 
		core->UnhideGCWindow();
	core->LoadProgress(100);
	return -1;
}
示例#8
0
static QScriptValue js_deprecatedGet(QScriptContext *context, QScriptEngine *qtengine)
{
    ScriptEngine *engine = static_cast<ScriptEngine *>(qtengine);
    const QScriptValue data = context->callee().property(QLatin1String("qbsdata"));
    engine->logger().qbsWarning()
            << ScriptEngine::tr("Property %1 is deprecated. Please use %2 instead.").arg(
                   data.property(0).toString(), data.property(1).toString());
    return data.property(2);
}
示例#9
0
static int executeFile(lua_State *L) {
	Kernel *pKernel = Kernel::getInstance();
	assert(pKernel);
	ScriptEngine *pSE = pKernel->getScript();
	assert(pSE);

	lua_pushbooleancpp(L, pSE->executeFile(luaL_checkstring(L, 1)));

	return 0;
}
示例#10
0
bool SoundEngine::registerScriptBindings() {
	Kernel *pKernel = Kernel::getInstance();
	BS_ASSERT(pKernel);
	ScriptEngine *pScript = pKernel->getScript();
	BS_ASSERT(pScript);
	lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
	BS_ASSERT(L);

	if (!LuaBindhelper::addFunctionsToLib(L, SFX_LIBRARY_NAME, SFX_FUNCTIONS)) return false;
	if (!LuaBindhelper::addConstantsToLib(L, SFX_LIBRARY_NAME, SFX_CONSTANTS)) return false;

	return true;
}
示例#11
0
bool Kernel::registerScriptBindings() {
	ScriptEngine *pScript = getScript();
	assert(pScript);
	lua_State *L = static_cast<lua_State *>(pScript->getScriptObject());
	assert(L);

	if (!LuaBindhelper::addFunctionsToLib(L, KERNEL_LIBRARY_NAME, KERNEL_FUNCTIONS)) return false;
	if (!LuaBindhelper::addFunctionsToLib(L, WINDOW_LIBRARY_NAME, WINDOW_FUNCTIONS)) return false;
	if (!LuaBindhelper::addFunctionsToLib(L, RESOURCE_LIBRARY_NAME, RESOURCE_FUNCTIONS)) return false;
	if (!LuaBindhelper::addFunctionsToLib(L, PERSISTENCE_LIBRARY_NAME, PERSISTENCE_FUNCTIONS)) return false;

	return true;
}
示例#12
0
void ScriptEngines::shutdownScripting() {
    _allScriptsMutex.lock();
    _stoppingAllScripts = true;
    ScriptEngine::_stoppingAllScripts = true;
    qCDebug(scriptengine) << "Stopping all scripts.... currently known scripts:" << _allKnownScriptEngines.size();

    QMutableSetIterator<ScriptEngine*> i(_allKnownScriptEngines);
    while (i.hasNext()) {
        ScriptEngine* scriptEngine = i.next();
        QString scriptName = scriptEngine->getFilename();

        // NOTE: typically all script engines are running. But there's at least one known exception to this, the
        // "entities sandbox" which is only used to evaluate entities scripts to test their validity before using
        // them. We don't need to stop scripts that aren't running.
        if (scriptEngine->isRunning()) {

            // If the script is running, but still evaluating then we need to wait for its evaluation step to
            // complete. After that we can handle the stop process appropriately
            if (scriptEngine->evaluatePending()) {
                while (scriptEngine->evaluatePending()) {

                    // This event loop allows any started, but not yet finished evaluate() calls to complete
                    // we need to let these complete so that we can be guaranteed that the script engine isn't
                    // in a partially setup state, which can confuse our shutdown unwinding.
                    QEventLoop loop;
                    QObject::connect(scriptEngine, &ScriptEngine::evaluationFinished, &loop, &QEventLoop::quit);
                    loop.exec();
                }
            }

            // We disconnect any script engine signals from the application because we don't want to do any
            // extra stopScript/loadScript processing that the Application normally does when scripts start
            // and stop. We can safely short circuit this because we know we're in the "quitting" process
            scriptEngine->disconnect(this);

            // Calling stop on the script engine will set it's internal _isFinished state to true, and result
            // in the ScriptEngine gracefully ending it's run() method.
            scriptEngine->stop();

            // We need to wait for the engine to be done running before we proceed, because we don't
            // want any of the scripts final "scriptEnding()" or pending "update()" methods from accessing
            // any application state after we leave this stopAllScripts() method
            qCDebug(scriptengine) << "waiting on script:" << scriptName;
            scriptEngine->waitTillDoneRunning();
            qCDebug(scriptengine) << "done waiting on script:" << scriptName;

            scriptEngine->deleteLater();

            // If the script is stopped, we can remove it from our set
            i.remove();
        }
    }
    _stoppingAllScripts = false;
    _allScriptsMutex.unlock();
    qCDebug(scriptengine) << "DONE Stopping all scripts....";
}
示例#13
0
void RegisterEntityMethods(const char* obj)
{
    ScriptEngine* engine = ScriptEngine::GetPtr();
    bool r;

    r=engine->RegisterMethod(obj, "string& GetShort()", asMETHOD(Entity, GetShort));
    assert(r);
    r = engine->RegisterMethod(obj, "void SetShort(string short)", asMETHOD(Entity, SetShort));
    assert(r);
    r = engine->RegisterMethod(obj, "Entity@ GetLocation()", asMETHOD(Entity, GetLocation));
    assert(r);
    r = engine->RegisterMethod(obj, "bool MoveTo(Entity@ obj)", asMETHOD(Entity, CanReceive));
    assert(r);
}
示例#14
0
QScriptValue ScriptEngine::js_loadExtension(QScriptContext *context, QScriptEngine *qtengine)
{
    ScriptEngine *engine = static_cast<ScriptEngine *>(qtengine);
    if (context->argumentCount() < 1) {
        return context->throwError(
                    ScriptEngine::tr("The loadExtension function requires "
                                     "an extension name."));
    }

    if (engine->m_extensionSearchPathsStack.isEmpty())
        return context->throwError(
                    ScriptEngine::tr("loadExtension: internal error. No search paths."));

    const QString uri = context->argument(0).toVariant().toString();
    if (engine->m_logger.debugEnabled()) {
        engine->m_logger.qbsDebug()
                << "[loadExtension] loading extension " << uri;
    }

    QString uriAsPath = uri;
    uriAsPath.replace(QLatin1Char('.'), QLatin1Char('/'));
    const QStringList searchPaths = engine->m_extensionSearchPathsStack.top();
    const QString dirPath = findExtensionDir(searchPaths, uriAsPath);
    if (dirPath.isEmpty()) {
        if (uri.startsWith(QLatin1String("qbs.")))
            return loadInternalExtension(context, engine, uri);

        return context->throwError(
                    ScriptEngine::tr("loadExtension: Cannot find extension '%1'. "
                                     "Search paths: %2.").arg(uri, searchPaths.join(
                                                                  QLatin1String(", "))));
    }

    QDirIterator dit(dirPath, QDir::Files | QDir::Readable);
    QScriptValueList values;
    try {
        while (dit.hasNext()) {
            const QString filePath = dit.next();
            if (engine->m_logger.debugEnabled()) {
                engine->m_logger.qbsDebug()
                        << "[loadExtension] importing file " << filePath;
            }
            values << engine->importFile(filePath, QScriptValue());
        }
    } catch (const ErrorInfo &e) {
        return context->throwError(e.toString());
    }

    return mergeExtensionObjects(values);
}
示例#15
0
QScriptValue ScriptEngine::exitScriptFunction(QScriptContext *context,
  QScriptEngine *engine)
{
  Q_UNUSED(context)

  ScriptEngine *scriptEngine = dynamic_cast<ScriptEngine *>(engine);

  if (scriptEngine != nullptr)
  {
    // signal exit
    emit scriptEngine->exitScript();
  }

  return engine->undefinedValue();
}
示例#16
0
QScriptValue ScriptEngine::nativePrint(QScriptContext *context, QScriptEngine *engine)
{
    QString result;
    for (int i = 0; i < context->argumentCount(); ++i) {
        if (i > 0)
            result.append(" ");
        result.append(context->argument(i).toString());
    }

    QScriptValue calleeData = context->callee().data();
    ScriptEngine *obj = qobject_cast<ScriptEngine*>(calleeData.toQObject());
    obj->printLine(result);

    return engine->undefinedValue();
}
示例#17
0
// sys_register_onChat( function_name )
// регистрирует функцию function_name как обработчик чат-сообщений
// обработчик должен иметь прототип Lua
// function onChat( senderObjectID, chatChannelID, chatText, senderName )
int sys_register_onChat( lua_State *L )
{
	ScriptEngine *se = ScriptEngine::getInstance();
	if( se == NULL )
	{
		log_error( LOG_ERROR, "sys_register_onChat(): ptr to ScriptEngine == NULL!\n" );
		return 0;
	}
	// получим первый арумент Lua функции sys_register_onChat как строку
	const char *funcName = lua_tolstring( L, 1, NULL );
	// funcName может быть NULL, если первый аргумент не был строкой. тогда обработчик отменится
	// зарегаем обработчик
	se->set_onChat_handler( funcName );
	return 0;
}
示例#18
0
ScriptEngine*
Session::createScriptEngine()
{
    // sessions are shared across compilations that might be in 
    // separate threads.
    ScopedLock<ReentrantMutex> sl( session_mtx );

    // get an empty scripting engine from the registry's factory
    ScriptEngine* engine = Registry::instance()->createScriptEngine();

    // install all the session scripts
    for( ScriptList::iterator i = scripts.begin(); i != scripts.end(); i++ )
        engine->install( i->get() );

    return engine;
}
示例#19
0
 void run() override {
   m_engine->m_engine->collectGarbage();
   QScriptValue result = m_engine->m_engine->evaluate(m_cmd);
   if (result.isError()) {
     m_engine->emitOutput(ScriptEngine::SyntaxError, result.toString());
   } else if (result.isUndefined()) {
     m_engine->emitOutput(ScriptEngine::UndefinedEvaluationResult,
                          "undefined");
   } else {
     if (qscriptvalue_cast<TScriptBinding::Void *>(result)) {
     } else {
       m_engine->emitOutput(ScriptEngine::EvaluationResult,
                            print(result, true));
     }
   }
 }
示例#20
0
NPC::NPC(ScriptEngine& engine, Scheduler& scheduler, const std::string& name, const std::string& sheetName,
		messaging::MessagePipe& messagePipe, EntityGrid& entityGrid, const std::string& regionName, const shapes::Point2D& location, const shapes::Size& size)
   : Actor(name, sheetName, messagePipe, entityGrid, location, size, 0.1f, DOWN)
{
   npcThread = engine.getNPCScript(this, regionName, entityGrid.getMapData()->getName(), name);
   scheduler.start(npcThread);
   DEBUG("NPC %s has a Thread with ID %d", name.c_str(), npcThread->getId());
}
示例#21
0
void Session::open() {

    try {
        setSessionState(SigningIn);

        ScriptEngine *engine = ScriptEngine::instance();
        m_scriptObject = engine->evaluate("new SessionHandler()");
        if (engine->hasUncaughtException()) {
            LogUtil::logException("Script Exception: %1\n"
                                  "In Session::open()", engine->uncaughtException());
            return;
        }

        QScriptValue setSession = m_scriptObject.property("setSession");
        QScriptValueList args;
        args.append(engine->toScriptValue(this));
        setSession.call(m_scriptObject, args);

        if (engine->hasUncaughtException()) {
            LogUtil::logException("Script Exception: %1\n"
                                  "In Session::open()", engine->uncaughtException());
        }
    } catch (GameException &exception) {
        LogUtil::logError("Exception in Session::open(): %1", exception.what());
    }
}
示例#22
0
bool Geometry::registerScriptBindings() {
	Kernel *pKernel = Kernel::getInstance();
	assert(pKernel);
	ScriptEngine *pScript = pKernel->getScript();
	assert(pScript);
	lua_State *L = static_cast< lua_State *>(pScript->getScriptObject());
	assert(L);

	if (!LuaBindhelper::addMethodsToClass(L, REGION_CLASS_NAME, REGION_METHODS)) return false;
	if (!LuaBindhelper::addMethodsToClass(L, WALKREGION_CLASS_NAME, REGION_METHODS)) return false;
	if (!LuaBindhelper::addMethodsToClass(L, WALKREGION_CLASS_NAME, WALKREGION_METHODS)) return false;

	if (!LuaBindhelper::setClassGCHandler(L, REGION_CLASS_NAME, r_delete)) return false;
	if (!LuaBindhelper::setClassGCHandler(L, WALKREGION_CLASS_NAME, r_delete)) return false;

	if (!LuaBindhelper::addFunctionsToLib(L, GEO_LIBRARY_NAME, GEO_FUNCTIONS)) return false;

	return true;
}
示例#23
0
Common::Error Sword25Engine::appStart() {
	// Initialize the graphics mode to ARGB8888
	Graphics::PixelFormat format = Graphics::PixelFormat(4, 8, 8, 8, 8, 16, 8, 0, 24);
	initGraphics(800, 600, true, &format);
	if (format != g_system->getScreenFormat())
		return Common::kUnsupportedColorMode;

	// Kernel initialization
	if (!Kernel::getInstance()->getInitSuccess()) {
		error("Kernel initialization failed.");
		return Common::kUnknownError;
	}

	// Load packages
	PackageManager *packageManagerPtr = Kernel::getInstance()->getPackage();
	if (getGameFlags() & GF_EXTRACTED) {
		if (!packageManagerPtr->loadDirectoryAsPackage(ConfMan.get("path"), "/"))
			return Common::kUnknownError;
	} else {
		if (!loadPackages())
			return Common::kUnknownError;
	}

	// Pass the command line to the script engine.
	ScriptEngine *scriptPtr = Kernel::getInstance()->getScript();
	if (!scriptPtr) {
		error("Script intialization failed.");
		return Common::kUnknownError;
	}

	// Set the game target for use in savegames
	setGameTarget(_targetName.c_str());

	Common::StringArray commandParameters;
	scriptPtr->setCommandLine(commandParameters);

	return Common::kNoError;
}
示例#24
0
CScriptArray* ContainerToScriptArray(const char* odecl, C& container)
{
    ScriptEngine* engine = ScriptEngine::GetPtr();
    size_t size = 0; //size of container.
    size_t i = 0; //for index.
    void* ptr = nullptr; //holds the individual element.
    asIObjectType* objtype = nullptr; //holds declaration.
    CScriptArray* ret  = nullptr;

    size = container.size();
    objtype = engine->GetBaseEngine()->GetObjectTypeByDecl(odecl);
    ret = CScriptArray::Create(objtype, size);

//we do the actual copy.
    for (auto it: container)
        {
            ptr = &it;
            ret->SetValue(i, ptr);
            i++;
        }

    return ret;
}
示例#25
0
/*!
 \brief

 \param tag
 \param fileInfo
 \param log
 \return bool
*/
bool PlayList::evaluateScript( Tag* tag, const QFileInfo& fileInfo, QString *log, QString *extInf, QString *sortBy ) const {

    if(script_.isEmpty()){
        return true;
    }

    ScriptEngine engine;
    QHash<QString,QVariant> frameFields = guiSettings->value("frameFields").toHash();

    //add all possible/specified id3v2 frames/ape items etc. to script, with empty array as value
    QHash< QString, QHash<QString,QStringList> > tagFrames = tag->frames(); //returns both ID3v2,asf,mp4,xiph and APE frames/items
    QStringList frameTypes = frameFields.keys(); //defined list of possible frames
    for(int j=0;j<frameTypes.size();j++){
        QString type = frameTypes[j]; //e.g. APE, ID3V2 etc.
        QStringList frameTypeKeys = frameFields[type].toStringList();
        QScriptValue array = engine.newArray(frameTypeKeys.size());
        QHash<QString,QStringList> tagTypeFrames = tagFrames[type];
        QStringList tagTypeFramesKeys = tagTypeFrames.keys();
        //loop for instance all ID3V2 frames
        QScriptValue v = engine.newArray(0);
        for(int i=0;i<frameTypeKeys.size();i++){
            v.setProperty(0, QScriptValue(&engine, "")); //set default value an empty array
            array.setProperty(frameTypeKeys[i].toUpper(), v);
        }//now add all frames from current tag
        for(int i=0;i<tagTypeFramesKeys.size();i++){
            QStringList list = tagTypeFrames[tagTypeFramesKeys[i]];
            for(int k=0;k<list.size();k++){
                v.setProperty(k, list[k]);
            }
            array.setProperty(tagTypeFramesKeys[i].toUpper(), v);
        }
        engine.globalObject().setProperty(type,array);
    }


    //add tag data  as variables to script
    engine.globalObject().setProperty("ARTIST",tag->artist());
    engine.globalObject().setProperty("ALBUM",tag->album());
    engine.globalObject().setProperty("GENRE",tag->genre());
    engine.globalObject().setProperty("TITLE",tag->title());
    engine.globalObject().setProperty("COMMENT",tag->comment());
    engine.globalObject().setProperty("YEAR",tag->year());
    engine.globalObject().setProperty("TRACK",tag->track());
    engine.globalObject().setProperty("LENGTH",tag->length());
    engine.globalObject().setProperty("BITRATE",tag->bitRate());
    engine.globalObject().setProperty("SAMPLERATE",tag->sampleRate());
    engine.globalObject().setProperty("CHANNELS",tag->channels());
    engine.globalObject().setProperty("TAGOK",tag->tagOk());
    engine.globalObject().setProperty("AUDIOPROPERTIESOK",tag->audioPropertiesOk());

    engine.globalObject().setProperty("FILENAME",fileInfo.fileName());
    engine.globalObject().setProperty("FILEPATH",fileInfo.filePath());    

    QScriptValue result = engine.evaluate( script_ );

    *extInf = engine.globalObject().property("EXTINF").toString();
    *sortBy = "";
    QScriptValue sortByValue = engine.globalObject().property("SORTBY");
    if( sortByValue.isValid() ){
        *sortBy = sortByValue.toString();
    }

    if( engine.hasUncaughtException() ){
        QString err = engine.uncaughtExceptionBacktrace().join("\n");
        log->append(err);
        return false;
    }
    bool res=false;
    if( result.isBool() ){
        res = result.toBool();
    }else{
        log->append("\nResult of evaluated script is not boolean");
    }
    return res;

}
示例#26
0
文件: Game.cpp 项目: BlackLotus/gemrb
/* Loads an area */
int Game::LoadMap(const char* ResRef, bool loadscreen)
{
	unsigned int i, ret;
	Map *newMap;
	PluginHolder<MapMgr> mM(IE_ARE_CLASS_ID);
	ScriptEngine *sE = core->GetGUIScriptEngine();

	//this shouldn't happen
	if (!mM) {
		return -1;
	}

	int index = FindMap(ResRef);
	if (index>=0) {
		return index;
	}

	bool hide = false;
	if (loadscreen && sE) {
		hide = core->HideGCWindow();
		sE->RunFunction("LoadScreen", "StartLoadScreen");
		sE->RunFunction("LoadScreen", "SetLoadScreen");
	}
	DataStream* ds = gamedata->GetResource( ResRef, IE_ARE_CLASS_ID );
	if (!ds) {
		goto failedload;
	}
	if(!mM->Open(ds)) {
		goto failedload;
	}
	newMap = mM->GetMap(ResRef, IsDay());
	if (!newMap) {
		goto failedload;
	}

	core->LoadProgress(100);

	ret = AddMap( newMap );

	//spawn creatures on a map already in the game
	//this feature exists in all blackisle games but not in bioware games
	if (core->HasFeature(GF_SPAWN_INI)) {
		newMap->LoadIniSpawn();
	}

	for (i = 0; i < PCs.size(); i++) {
		if (stricmp( PCs[i]->Area, ResRef ) == 0) {
			newMap->AddActor( PCs[i], false );
		}
	}

	PlacePersistents(newMap, ResRef);

	if (hide) {
		core->UnhideGCWindow();
	}
	newMap->InitActors();

	return ret;
failedload:
	if (hide) {
		core->UnhideGCWindow();
	}
	core->LoadProgress(100);
	return -1;
}
示例#27
0
void Main()
{
	ResourceLoader resources;

	auto sampler = SamplerState(SamplerState::Default2D);
	sampler.filter = TextureFilter::MinMagMipPoint;
	Graphics2D::SetSamplerState(sampler);

	Window::Resize(320 * 2, 240 * 2);
	Window::SetTitle(L"まちへかえろう(仮)");

	Array<HurdleObject> hurdles;
	Array<BuildingLayer> buildingLayers;
	Array<BuildingLayer2> buildingLayers2;

	Map::instance().init(40, 15);

	for (int i = 0; i < 40; i++)
	{
		Map::instance().set(i, 14, 5);
		Map::instance().set(i, 13, 5);
		Map::instance().set(i, 12, 4);
		Map::instance().set(i, 11, 3);
		Map::instance().set(i, 10, 3);
		Map::instance().set(i, 9, 2);
		Map::instance().set(i, 8, 1);
	}
	auto viewLeft = 0.0;
	auto mycharDead = false;
	ScreenState currentState = ScreenState::InTitle, prevState = currentState;
	bool prevSpacePressed = false;

	auto TitleTimer = TimerMillisec();

	ScriptEngine asEngine;
	asEngine.RegisterMethod(L"int getAt(double x, double y)", &Map::getAt, Map::instance());
	asEngine.RegisterProperty(L"double _viewX", &viewLeft);
	asEngine.RegisterProperty(L"bool _isGameOvered", &mycharDead);
	asEngine.RegisterFunction(L"void playJumpSound()", PlayJumpSound);
	auto context_mychar = asEngine.CreateContextFromScript(L"res/scripts/Mychar.as");

	Record::instance().init();

	int fc = 0;
	while (System::Update())
	{
		bool spacePressedInFrame = !prevSpacePressed && Input::KeySpace.pressed;
		prevSpacePressed = Input::KeySpace.pressed;

		asEngine.setFrameCount(fc);

		switch (currentState)
		{
		case ScreenState::InTitle:
			if (!TitleTimer.isActive) TitleTimer.start();
			renderBackgrounds(viewLeft, resources);
			renderBuildingLayers(buildingLayers, buildingLayers2, resources);
			renderMap(viewLeft, resources);
			renderTitle(TitleTimer.elapsed(), resources);
			renderCurrentMax();

			if (spacePressedInFrame)
			{
				// GameInit
				SoundAsset(SoundResourceLoader::decide).play();
				viewLeft = 0.0;
				mycharDead = false;
				context_mychar.Reenter();
				buildingLayers.clear();
				buildingLayers2.clear();
				hurdles.clear();
				currentState = ScreenState::Gaming;
			}
			break;
		case ScreenState::Gaming:
			// appear hurdles at random
			if (RandomBool(0.02))
			{
				if (hurdles.empty() || hurdles.back().getPos().x - (viewLeft + 320.0f) < -48.0f)
				{
					// allocate space least 48 logical-pixels
					hurdles.emplace_back(HurdleObject(Vec2(viewLeft + 320.0f, 8.0f * 16.0f + 8.0f)));
				}
			}
			// appear building at random
			if (RandomBool(0.02 / 30.0))
			{
				if (buildingLayers.empty() || buildingLayers.back().getPos().x < 0.0f)
				{
					buildingLayers.emplace_back(BuildingLayer(Vec2(320.0f, -60.0f)));
				}
			}
			if (RandomBool(0.01 / 30.0))
			{
				if (buildingLayers2.empty() || buildingLayers2.back().getPos().x < 0.0f)
				{
					buildingLayers2.emplace_back(BuildingLayer2(Vec2(320.0f, -60.0f)));
				}
			}

			asEngine.setFrameCount(fc);
			context_mychar.Execute();

			renderBackgrounds(viewLeft, resources);
			renderBuildingLayers(buildingLayers, buildingLayers2, resources);
			renderMap(viewLeft, resources);
			if (renderHurdlesAndHitTest(viewLeft, context_mychar.GetGlobalDoubleVec2(L"x", L"y"), hurdles, resources))
			{
				if (!mycharDead) SoundAsset(SoundResourceLoader::died).play();
				mycharDead = true;
			}
			renderPlayer(viewLeft, context_mychar.GetGlobalDouble(L"angle"), context_mychar.GetGlobalDoubleVec2(L"x", L"y"), resources);
			renderInfo(toScore(context_mychar.GetGlobalDouble(L"x")));

			// Host Processes
			if (mycharDead && context_mychar.GetGlobalDouble(L"x") < viewLeft - 120.0f)
			{
				// update record
				Record::instance().recordScore(toScore(context_mychar.GetGlobalDouble(L"x")));
				currentState = ScreenState::Result;
			}
			break;
		case ScreenState::Result:
			renderBackgrounds(viewLeft, resources);
			renderBuildingLayers(buildingLayers, buildingLayers2, resources);
			renderMap(viewLeft, resources);
			renderHurdlesAndHitTest(viewLeft, context_mychar.GetGlobalDoubleVec2(L"x", L"y"), hurdles, resources);
			renderResult(toScore(context_mychar.GetGlobalDouble(L"x")), Record::instance().isUpdated(), fc);

			if (spacePressedInFrame)
			{
				// GameInit
				SoundAsset(SoundResourceLoader::decide).play();
				TitleTimer.reset();
				currentState = ScreenState::InTitle;
			}
			break;
		}
		if (prevState != currentState)
		{
			fc = 0;
		}
		prevState = currentState;

		// Common Postprocesses
		fc++;
		viewLeft += 2.5f;
	}

	Map::instance().clean();
}
示例#28
0
void BotScheduler::installTo( ScriptEngine &eng )
{
	eng.regObject( "BotScheduler", this );
}
示例#29
0
Logger Process::logger() const
{
    ScriptEngine *scriptEngine = static_cast<ScriptEngine *>(engine());
    return scriptEngine->logger();
}
示例#30
0
文件: Skill.cpp 项目: noam-c/EDEn
std::shared_ptr<UsableScript> Skill::createScript(ScriptEngine& scriptEngine)
{
   return scriptEngine.createSkillScript(*this);
}