IC bool operator() (u32 v0, u32 v1) const { return (ai().level_graph().vertex(v0)->position().xz() < ai().level_graph().vertex(v1)->position().xz()); }
void CLevel::script_gc () { lua_gc (ai().script_engine().lua(), LUA_GCSTEP, psLUA_GCSTEP); }
float CEnemyManager::evaluate (const CEntityAlive *object) const { // Msg ("[%6d] enemy manager %s evaluates %s",Device.dwTimeGlobal,*m_object->cName(),*object->cName()); bool actor = (object->CLS_ID == CLSID_OBJECT_ACTOR); if (actor) m_ready_to_save = false; const CAI_Stalker *stalker = smart_cast<const CAI_Stalker*>(object); bool wounded = stalker ? stalker->wounded(&m_object->movement().restrictions()) : false; if (wounded) { if (m_stalker && m_stalker->agent_manager().enemy().assigned_wounded(object,m_stalker)) return (0.f); float distance = m_object->Position().distance_to_sqr(object->Position()); return (distance); } float penalty = 10000.f; // if we are hit if (object->ID() == m_object->memory().hit().last_hit_object_id()) { if (actor) penalty -= 1500.f; else penalty -= 500.f; } // if we see object if (m_object->memory().visual().visible_now(object)) penalty -= 1000.f; // if object is actor and he/she sees us // if (actor) { // if (smart_cast<const CActor*>(object)->memory().visual().visible_now(m_object)) // penalty -= 900.f; // } // else { // // if object is npc and it sees us // const CCustomMonster *monster = smart_cast<const CCustomMonster*>(object); // if (monster && monster->memory().visual().visible_now(m_object)) // penalty -= 300.f; // } #ifdef USE_EVALUATOR ai().ef_storage().non_alife().member_item() = 0; ai().ef_storage().non_alife().enemy_item() = 0; ai().ef_storage().non_alife().member() = m_object; ai().ef_storage().non_alife().enemy() = object; float distance = m_object->Position().distance_to_sqr(object->Position()); return ( penalty + distance/100.f + ai().ef_storage().m_pfVictoryProbability->ffGetValue()/100.f ); #else // USE_EVALUATOR float distance = m_object->Position().distance_to_sqr(object->Position()); return ( 1000.f*(visible ? 0.f : 1.f) + distance ); #endif // USE_EVALUATOR }
bool CScriptEntity::bfAssignMovement(CScriptEntityAction *tpEntityAction) { CScriptMovementAction &l_tMovementAction = tpEntityAction->m_tMovementAction; if (l_tMovementAction.m_bCompleted) return (false); CEntityAlive *entity_alive = smart_cast<CEntityAlive*>(this); if (entity_alive && !entity_alive->g_Alive()) { l_tMovementAction.m_bCompleted = true; return (false); } if (!m_monster) { ai().script_engine().script_log(eLuaMessageTypeError,"Cannot assign a movement action not to a monster!"); return (true); } switch (l_tMovementAction.m_tGoalType) { case CScriptMovementAction::eGoalTypeObject : { CGameObject *l_tpGameObject = smart_cast<CGameObject*>(l_tMovementAction.m_tpObjectToGo); #ifdef DEBUG THROW2 (l_tpGameObject,"eGoalTypeObject specified, but no object passed!"); #else R_ASSERT(l_tpGameObject); #endif m_monster->movement().set_path_type(MovementManager::ePathTypeLevelPath); // Msg ("%6d Object %s, position [%f][%f][%f]",Device.dwTimeGlobal,*l_tpGameObject->cName(),VPUSH(l_tpGameObject->Position())); m_monster->movement().detail().set_dest_position(l_tpGameObject->Position()); m_monster->movement().set_level_dest_vertex(l_tpGameObject->ai_location().level_vertex_id()); break; } case CScriptMovementAction::eGoalTypePatrolPath : { m_monster->movement().set_path_type (MovementManager::ePathTypePatrolPath); m_monster->movement().patrol().set_path (l_tMovementAction.m_path,l_tMovementAction.m_path_name); m_monster->movement().patrol().set_start_type (l_tMovementAction.m_tPatrolPathStart); m_monster->movement().patrol().set_route_type (l_tMovementAction.m_tPatrolPathStop); m_monster->movement().patrol().set_random (l_tMovementAction.m_bRandom); if (l_tMovementAction.m_previous_patrol_point != u32(-1)) { m_monster->movement().patrol().set_previous_point(l_tMovementAction.m_previous_patrol_point); } break; } case CScriptMovementAction::eGoalTypePathPosition : { m_monster->movement().set_path_type(MovementManager::ePathTypeLevelPath); m_monster->movement().detail().set_dest_position(l_tMovementAction.m_tDestinationPosition); u32 vertex_id; vertex_id = ai().level_graph().vertex(object().ai_location().level_vertex_id(),l_tMovementAction.m_tDestinationPosition); if (!ai().level_graph().valid_vertex_id(vertex_id)) vertex_id = ai().level_graph().check_position_in_direction(object().ai_location().level_vertex_id(),object().Position(),l_tMovementAction.m_tDestinationPosition); #ifdef DEBUG if (!ai().level_graph().valid_vertex_id(vertex_id)) { string256 S; sprintf_s (S,"Cannot find corresponding level vertex for the specified position [%f][%f][%f] for monster %s",VPUSH(l_tMovementAction.m_tDestinationPosition),*m_monster->cName()); THROW2 (ai().level_graph().valid_vertex_id(vertex_id),S); } #endif m_monster->movement().level_path().set_dest_vertex(vertex_id); break; } case CScriptMovementAction::eGoalTypePathNodePosition : { VERIFY(ai().level_graph().valid_vertex_id(l_tMovementAction.m_tNodeID)); m_monster->movement().set_path_type (MovementManager::ePathTypeLevelPath); m_monster->movement().detail().set_dest_position (l_tMovementAction.m_tDestinationPosition); m_monster->movement().level_path().set_dest_vertex (l_tMovementAction.m_tNodeID); break; } case CScriptMovementAction::eGoalTypeNoPathPosition : { m_monster->movement().set_path_type(MovementManager::ePathTypeLevelPath); if (m_monster->movement().detail().path().empty() || (m_monster->movement().detail().path()[m_monster->movement().detail().path().size() - 1].position.distance_to(l_tMovementAction.m_tDestinationPosition) > .1f)) { m_monster->movement().detail().m_path.resize(2); m_monster->movement().detail().m_path[0].position = object().Position(); m_monster->movement().detail().m_path[1].position = l_tMovementAction.m_tDestinationPosition; m_monster->movement().detail().m_current_travel_point = 0; } if (m_monster->movement().detail().m_path[1].position.similar(object().Position(),.2f)) l_tMovementAction.m_bCompleted = true; break; } default : { m_monster->movement().set_desirable_speed(0.f); return (l_tMovementAction.m_bCompleted = true); } } if (m_monster->movement().actual_all() && m_monster->movement().path_completed()) l_tMovementAction.m_bCompleted = true; return (!l_tMovementAction.m_bCompleted); }
CLevel::~CLevel() { xr_delete (g_player_hud); delete_data (hud_zones_list); hud_zones_list = NULL; Msg ("- Destroying level"); Engine.Event.Handler_Detach (eEntitySpawn, this); Engine.Event.Handler_Detach (eEnvironment, this); Engine.Event.Handler_Detach (eChangeTrack, this); Engine.Event.Handler_Detach (eDemoPlay, this); Engine.Event.Handler_Detach (eChangeRP, this); if (ph_world) { ph_world->Destroy (); xr_delete (ph_world); } // destroy PSs for (POIt p_it=m_StaticParticles.begin(); m_StaticParticles.end()!=p_it; ++p_it) CParticlesObject::Destroy(*p_it); m_StaticParticles.clear (); // Unload sounds // unload prefetched sounds sound_registry.clear (); // unload static sounds for (u32 i=0; i<static_Sounds.size(); ++i){ static_Sounds[i]->destroy(); xr_delete (static_Sounds[i]); } static_Sounds.clear (); xr_delete (m_level_sound_manager); xr_delete (m_space_restriction_manager); xr_delete (m_seniority_hierarchy_holder); xr_delete (m_client_spawn_manager); xr_delete (m_autosave_manager); #ifdef DEBUG xr_delete (m_debug_renderer); #endif if (!g_dedicated_server) ai().script_engine().remove_script_process(ScriptEngine::eScriptProcessorLevel); xr_delete (game); xr_delete (game_events); #ifdef SPAWN_ANTIFREEZE xr_delete(spawn_events); #endif //by Dandy //destroy fog of war // xr_delete (m_pFogOfWar); //destroy bullet manager xr_delete (m_pBulletManager); //----------------------------------------------------------- xr_delete (pStatGraphR); xr_delete (pStatGraphS); //----------------------------------------------------------- xr_delete (m_ph_commander); xr_delete (m_ph_commander_scripts); //----------------------------------------------------------- pObjects4CrPr.clear(); pActors4CrPr.clear(); ai().unload (); //----------------------------------------------------------- #ifdef DEBUG xr_delete (m_level_debug); #endif //----------------------------------------------------------- xr_delete (m_map_manager); delete_data (m_game_task_manager); // xr_delete (m_pFogOfWarMngr); // here we clean default trade params // because they should be new for each saved/loaded game // and I didn't find better place to put this code in CTradeParameters::clean (); if(g_tutorial && g_tutorial->m_pStoredInputReceiver==this) g_tutorial->m_pStoredInputReceiver = NULL; if(g_tutorial2 && g_tutorial2->m_pStoredInputReceiver==this) g_tutorial2->m_pStoredInputReceiver = NULL; if (IsDemoPlay()) { StopPlayDemo(); } xr_delete(m_msg_filter); if (IsDemoSave()) { StopSaveDemo(); } }
void nl80211::setup_family(boost::system::error_code& ec) { genetlink::message msg; msg.flags(netlink::message::request | netlink::message::ack); msg.command(genetlink::message::cmd_get_family); msg.version(1); msg.push_attr(genetlink::message::attr_family_name, "nl80211", 8); _gnl.send(msg.cbuffer()); size_t rbytes = _gnl.receive(boost::asio::buffer(_buffer)); for (netlink::message_iterator mit(_buffer, rbytes); mit; ++mit) { if (mit.type() == netlink::message::error) { ec = boost::system::error_code(mit.error(), boost::system::system_category()); return; } if (mit.type() == netlink::message::min_type) { genetlink::message rmsg(mit.get()); for (netlink::attribute_iterator ai(rmsg); ai; ++ai) { switch (ai.type()) { case genetlink::message::attr_family_id: _family = *ai.get<uint16>(); break; case genetlink::message::attr_family_name: BOOST_ASSERT(!strcmp(ai.get<const char>(), "nl80211")); break; case genetlink::message::attr_version: _version = *ai.get<uint32>(); break; case genetlink::message::attr_hdrsize: _hdrsize = *ai.get<uint32>(); break; case genetlink::message::attr_mcast_groups: for (netlink::attribute_iterator ali(rmsg, ai); ali; ++ali) { const char* name = nullptr; uint32 id = 0; for (netlink::attribute_iterator aei(rmsg, ali); aei; ++aei) { switch (aei.type()) { case genetlink::message::attr_mcast_name: name = aei.get<const char>(); break; case genetlink::message::attr_mcast_id: id = *aei.get<uint32>(); break; } } if (name && !strcmp(name, "mlme")) { _mlne_mcast_id = id; break; } } break; } } break; } } }
FuncAnalysis do_analyze_collect(const Index& index, Context const inputCtx, CollectedInfo& collect, ClassAnalysis* clsAnalysis, const std::vector<Type>* knownArgs) { auto const ctx = adjust_closure_context(inputCtx); FuncAnalysis ai(ctx); Trace::Bump bumper{Trace::hhbbc, kTraceFuncBump, is_trace_function(ctx.cls, ctx.func)}; FTRACE(2, "{:-^70}\n-- {}\n", "Analyze", show(ctx)); /* * Set of RPO ids that still need to be visited. * * Initially, we need each entry block in this list. As we visit * blocks, we propagate states to their successors and across their * back edges---when state merges cause a change to the block * stateIn, we will add it to this queue so it gets visited again. */ auto incompleteQ = prepare_incompleteQ(index, ai, clsAnalysis, knownArgs); /* * There are potentially infinitely growing types when we're using * union_of to merge states, so occasonially we need to apply a * widening operator. * * Currently this is done by having a straight-forward hueristic: if * you visit a block too many times, we'll start doing all the * merges with the widening operator until we've had a chance to * visit the block again. We must then continue iterating in case * the actual fixed point is higher than the result of widening. * * Terminiation is guaranteed because the widening operator has only * finite chains in the type lattice. */ auto nonWideVisits = std::vector<uint32_t>(ctx.func->nextBlockId); // For debugging, count how many times basic blocks get interpreted. auto interp_counter = uint32_t{0}; /* * Iterate until a fixed point. * * Each time a stateIn for a block changes, we re-insert the block's * rpo ID in incompleteQ. Since incompleteQ is ordered, we'll * always visit blocks with earlier RPO ids first, which hopefully * means less iterations. */ while (!incompleteQ.empty()) { auto const blk = ai.rpoBlocks[incompleteQ.pop()]; if (nonWideVisits[blk->id]++ > options.analyzeFuncWideningLimit) { nonWideVisits[blk->id] = 0; } FTRACE(2, "block #{}\nin {}{}", blk->id, state_string(*ctx.func, ai.bdata[blk->id].stateIn), property_state_string(collect.props)); ++interp_counter; auto propagate = [&] (php::Block& target, const State& st) { auto const needsWiden = nonWideVisits[target.id] >= options.analyzeFuncWideningLimit; // We haven't optimized the widening operator much, because it // doesn't happen in practice right now. We want to know when // it starts happening: if (needsWiden) { std::fprintf(stderr, "widening in %s on %s\n", ctx.unit->filename->data(), ctx.func->name->data()); } FTRACE(2, " {}-> {}\n", needsWiden ? "widening " : "", target.id); FTRACE(4, "target old {}", state_string(*ctx.func, ai.bdata[target.id].stateIn)); auto const changed = needsWiden ? widen_into(ai.bdata[target.id].stateIn, st) : merge_into(ai.bdata[target.id].stateIn, st); if (changed) { incompleteQ.push(rpoId(ai, &target)); } FTRACE(4, "target new {}", state_string(*ctx.func, ai.bdata[target.id].stateIn)); }; auto stateOut = ai.bdata[blk->id].stateIn; auto interp = Interp { index, ctx, collect, blk, stateOut }; auto flags = run(interp, propagate); if (flags.returned) { ai.inferredReturn = union_of(std::move(ai.inferredReturn), std::move(*flags.returned)); } } ai.closureUseTypes = std::move(collect.closureUseTypes); if (ctx.func->isGenerator) { if (ctx.func->isAsync) { // Async generators always return AsyncGenerator object. ai.inferredReturn = objExact(index.builtin_class(s_AsyncGenerator.get())); } else { // Non-async generators always return Generator object. ai.inferredReturn = objExact(index.builtin_class(s_Generator.get())); } } else if (ctx.func->isAsync) { // Async functions always return WaitH<T>, where T is the type returned // internally. ai.inferredReturn = wait_handle(index, ai.inferredReturn); } /* * If inferredReturn is TBottom, the callee didn't execute a return * at all. (E.g. it unconditionally throws, or is an abstract * function body.) * * In this case, we leave the return type as TBottom, to indicate * the same to callers. */ assert(ai.inferredReturn.subtypeOf(TGen)); // For debugging, print the final input states for each block. FTRACE(2, "{}", [&] { auto const bsep = std::string(60, '=') + "\n"; auto const sep = std::string(60, '-') + "\n"; auto ret = folly::format( "{}function {} ({} block interps):\n{}", bsep, show(ctx), interp_counter, bsep ).str(); for (auto& bd : ai.bdata) { ret += folly::format( "{}block {}:\nin {}", sep, ai.rpoBlocks[bd.rpoId]->id, state_string(*ctx.func, bd.stateIn) ).str(); } ret += sep + bsep; folly::format(&ret, "Inferred return type: {}\n", show(ai.inferredReturn)); ret += bsep; return ret; }()); return ai; }
void xrServer::Process_event_destroy (NET_Packet& P, ClientID sender, u32 time, u16 ID, NET_Packet* pEPack) { u32 MODE = net_flags(TRUE,TRUE); // Parse message u16 id_dest = ID; #ifdef DEBUG if( dbg_net_Draw_Flags.test( dbg_destroy ) ) Msg ("sv destroy object %s [%d]", ent_name_safe(id_dest).c_str(), Device.dwFrame); #endif CSE_Abstract* e_dest = game->get_entity_from_eid (id_dest); // кто должен быть уничтожен if (!e_dest) { #ifndef MASTER_GOLD Msg ("! SV:ge_destroy: [%d] not found on server",id_dest); #endif // #ifndef MASTER_GOLD return; }; R_ASSERT (e_dest); xrClientData *c_dest = e_dest->owner; // клиент, чей юнит R_ASSERT (c_dest); xrClientData *c_from = ID_to_client(sender); // клиент, кто прислал R_ASSERT (c_dest == c_from); // assure client ownership of event u16 parent_id = e_dest->ID_Parent; #ifdef MP_LOGGING Msg("- SV: Process destroy: parent [%d] item [%d][%s]", parent_id, id_dest, e_dest->name()); #endif //#ifdef MP_LOGGING //--------------------------------------------- NET_Packet P2, *pEventPack = pEPack; P2.w_begin (M_EVENT_PACK); //--------------------------------------------- // check if we have children if (!e_dest->children.empty()) { if (!pEventPack) pEventPack = &P2; while (!e_dest->children.empty()) Process_event_destroy (P,sender,time,*e_dest->children.begin(), pEventPack); }; if (0xffff == parent_id && NULL == pEventPack) { SendBroadcast (BroadcastCID,P,MODE); } else { NET_Packet tmpP; if (0xffff != parent_id && Process_event_reject(P,sender,time,parent_id,ID,false)) { game->u_EventGen(tmpP, GE_OWNERSHIP_REJECT, parent_id); tmpP.w_u16(id_dest); tmpP.w_u8(1); if (!pEventPack) pEventPack = &P2; pEventPack->w_u8(u8(tmpP.B.count)); pEventPack->w(&tmpP.B.data, tmpP.B.count); }; game->u_EventGen(tmpP, GE_DESTROY, id_dest); pEventPack->w_u8(u8(tmpP.B.count)); pEventPack->w(&tmpP.B.data, tmpP.B.count); }; if (NULL == pEPack && NULL != pEventPack) { SendBroadcast (BroadcastCID, *pEventPack, MODE); } // Everything OK, so perform entity-destroy if (e_dest->m_bALifeControl && ai().get_alife()) { game_sv_Single *_game = smart_cast<game_sv_Single*>(game); VERIFY (_game); if (ai().alife().objects().object(id_dest,true)) _game->alife().release (e_dest,false); } if (game) game->OnDestroyObject (e_dest->ID); entity_Destroy (e_dest); }
GameGraph::_GRAPH_ID CALifeSmartTerrainTask::game_vertex_id () const { VERIFY3 (ai().game_graph().valid_vertex_id(patrol_point().game_vertex_id()),*m_patrol_path_name,*m_patrol_point->name()); return (patrol_point().game_vertex_id()); }
Variant ObjectMethodExpression::eval(VariableEnvironment &env) const { String name(m_name->get(env)); Variant obj(m_obj->eval(env)); if (!obj.is(KindOfObject)) { raise_error("Call to a member function %s() on a non-object", name.c_str()); } #ifdef ENABLE_LATE_STATIC_BINDING EvalFrameInjection::EvalStaticClassNameHelper helper(obj.toObject()); #endif Variant cobj(env.currentObject()); const MethodStatement *ms = NULL; if (cobj.is(KindOfObject) && obj.getObjectData() == cobj.getObjectData()) { // Have to try current class first for private method const ClassStatement *cls = env.currentClassStatement(); if (cls) { const MethodStatement *ccms = cls->findMethod(name.c_str()); if (ccms && ccms->getModifiers() & ClassStatement::Private) { ms = ccms; } } } if (!ms) { ms = obj.getObjectData()->getMethodStatement(name.data()); } SET_LINE; if (ms) { return strongBind(ms->invokeInstanceDirect(toObject(obj), env, this)); } // Handle builtins MethodCallPackage mcp1; mcp1.methodCall(obj, name, -1); const CallInfo* ci = mcp1.ci; // If the lookup failed methodCall() must throw an exception, // so if we reach here ci must not be NULL ASSERT(ci); unsigned int count = m_params.size(); if (count <= 6) { CVarRef a0 = (count > 0) ? evalParam(env, ci, 0) : null; CVarRef a1 = (count > 1) ? evalParam(env, ci, 1) : null; CVarRef a2 = (count > 2) ? evalParam(env, ci, 2) : null; CVarRef a3 = (count > 3) ? evalParam(env, ci, 3) : null; CVarRef a4 = (count > 4) ? evalParam(env, ci, 4) : null; CVarRef a5 = (count > 5) ? evalParam(env, ci, 5) : null; return strongBind((ci->getMethFewArgs())(mcp1, count, a0, a1, a2, a3, a4, a5)); } if (RuntimeOption::UseArgArray) { ArgArray *args = prepareArgArray(env, ci, count); return strongBind((ci->getMeth())(mcp1, args)); } ArrayInit ai(count); for (unsigned int i = 0; i < count; ++i) { if (ci->mustBeRef(i)) { ai.setRef(m_params[i]->refval(env)); } else if (ci->isRef(i)) { ai.setRef(m_params[i]->refval(env, 0)); } else { ai.set(m_params[i]->eval(env)); } } return strongBind((ci->getMeth())(mcp1, Array(ai.create()))); }
bool VESPERSXASDataLoader::loadFromFile(const QString &filepath, bool setMetaData, bool setRawDataSources, bool createDefaultAnalysisBlocks) { // Currently don't have meta data. Q_UNUSED(setMetaData) Q_UNUSED(setRawDataSources) Q_UNUSED(createDefaultAnalysisBlocks) AMXASScan *scan = qobject_cast<AMXASScan *>(scan_); if (!scan) { AMErrorMon::alert(0, 0, "VESPERS XAS File Loader: Could not load XAS data into a non-XAS scan."); return false; } // Clear the old scan axes to ensure we don't have any extras. scan->clearRawDataCompletely(); scan->rawData()->addScanAxis( AMAxisInfo("eV", 0, "Incident Energy", "eV") ); QFile file(filepath); if(!file.open(QIODevice::ReadOnly)) { AMErrorMon::error(0, -1, "XASFileLoader parse error while loading scan data from file."); return false; } QFile spectra; QVector<int> data; QTextStream in(&file); QString line; QStringList lineTokenized; // Need to determine if the single element or four element vortex detector was used. Also need to determine which ion chambers were used for I0 and It. // First two lines are useless. line = in.readLine(); line = in.readLine(); line = in.readLine(); if (line.contains("#(2)")) line = in.readLine(); bool usingVortex = line.contains("IOC1607-004") || line.contains("dxp1607-B21-04"); if (usingVortex) { data.resize(2048); QString temp(filepath); temp.chop(4); spectra.setFileName(temp+"_spectra.dat"); if(!spectra.open(QIODevice::ReadOnly)) { AMErrorMon::error(0, -1, QString("XASFileLoader parse error while loading scan spectra data from %1.").arg(spectra.fileName())); return false; } } else spectra.setFileName(""); QTextStream spectraStream(&spectra); QString spectraLine; QStringList spectraTokenized; while ((line = in.readLine()).contains("#")) { //Do nothing } // Clear any old data so we can start fresh. scan->clearRawDataPointsAndMeasurements(); // Some setup variables. int axisValueIndex = 0; if (usingVortex) { for (int i = 0; i < scan_->rawDataSourceCount()-1; i++) scan_->rawData()->addMeasurement(AMMeasurementInfo(scan_->rawDataSources()->at(i)->name(), scan_->rawDataSources()->at(i)->description())); QList<AMAxisInfo> axisInfo; AMAxisInfo ai("Energy", 2048, "Energy", "eV"); ai.increment = 10; ai.start = AMNumber(0); ai.isUniform = true; axisInfo << ai; scan_->rawData()->addMeasurement(AMMeasurementInfo(scan_->rawDataSources()->at(scan_->rawDataSourceCount()-1)->name(), scan_->rawDataSources()->at(scan_->rawDataSourceCount()-1)->description(), "eV", axisInfo)); } else { for (int i = 0; i < scan_->rawDataSourceCount(); i++) scan_->rawData()->addMeasurement(AMMeasurementInfo(scan_->rawDataSources()->at(i)->name(), scan_->rawDataSources()->at(i)->description())); } while (!in.atEnd()) { lineTokenized << line.split(", "); scan->rawData()->beginInsertRows(1, -1); scan_->rawData()->setAxisValue(0, axisValueIndex, lineTokenized.at(1).toDouble()); // This isn't the most efficient way of putting the spectra data in, but it will do for the time being. if (usingVortex) { // Only going to rawDataSourceCount-1 because the last raw data source is the 2D spectra scan and requires its own method of entering the data. for (int i = 0; i < scan_->rawDataSourceCount()-1; i++) scan_->rawData()->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble()); spectraTokenized.clear(); spectraLine = spectraStream.readLine(); spectraTokenized << spectraLine.split(","); for (int j = 0; j < 2048; j++) data[j] = spectraTokenized.at(j).toInt(); scan_->rawData()->setValue(axisValueIndex, scan_->rawDataSourceCount()-1, data.constData()); } else { // In transmission, there is no 2D spectra. Go through all the data sources. for (int i = 0; i < scan_->rawDataSourceCount(); i++) scan_->rawData()->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble()); } scan->rawData()->endInsertRows(); axisValueIndex++; line = in.readLine(); lineTokenized.clear(); } file.close(); if (usingVortex) spectra.close(); return true; }
void CALifeMonsterDetailPathManager::actualize () { m_path.clear (); typedef GraphEngineSpace::CGameVertexParams CGameVertexParams; CGameVertexParams temp = CGameVertexParams(object().m_tpaTerrain); bool failed = !ai().graph_engine().search ( ai().game_graph(), object().get_object().m_tGraphID, m_destination.m_game_vertex_id, &m_path, temp ); #ifdef DEBUG if (failed) { Msg ("! %s couldn't build game path from",object().get_object().name_replace()); { const CGameGraph::CVertex *vertex = ai().game_graph().vertex(object().get_object().m_tGraphID); Msg ( "! [%d][%s][%f][%f][%f]", object().get_object().m_tGraphID, *ai().game_graph().header().level( vertex->level_id() ).name(), VPUSH(vertex->level_point()) ); Msg ("! game_graph_mask -> [ %d, %d, %d, %d]", vertex->vertex_type()[0], vertex->vertex_type()[1], vertex->vertex_type()[2], vertex->vertex_type()[3]); } { const CGameGraph::CVertex *vertex = ai().game_graph().vertex(m_destination.m_game_vertex_id); Msg ( "! [%d][%s][%f][%f][%f]", m_destination.m_game_vertex_id, *ai().game_graph().header().level( vertex->level_id() ).name(), VPUSH(vertex->level_point()) ); Msg ("! game_graph_mask -> [ %d, %d, %d, %d]", vertex->vertex_type()[0], vertex->vertex_type()[1], vertex->vertex_type()[2], vertex->vertex_type()[3]); } Msg ("! List of available game_graph masks:"); xr_vector<GameGraph::STerrainPlace>::iterator I = object().m_tpaTerrain.begin(); xr_vector<GameGraph::STerrainPlace>::iterator E = object().m_tpaTerrain.end(); for ( ; I != E; ++I) { Msg ("! [%d , %d , %d , %d]",(*I).tMask[0],(*I).tMask[1],(*I).tMask[2],(*I).tMask[3]); }; } #endif if (failed) return; VERIFY (!m_path.empty()); if (m_path.size() == 1) { VERIFY (m_path.back() == object().get_object().m_tGraphID); return; } m_walked_distance = 0.f; std::reverse (m_path.begin(),m_path.end()); VERIFY (m_path.back() == object().get_object().m_tGraphID); }
int main() { int iwinner; char board[15][15]={0}; int comp[15][15]={0}; int user[15][15]={0}; step p1,p2,n; print_board(board); int count = 0; while(1) { if(count>=225) { break; } p1=get_input_step(board,WHITE); printf(">>>>>>>>>>>>>>>>>>>>>>>>>>\n"); //p1=ten(board,BLACK); board[p1.row][p1.col]=p1.player; print_board(board); count++; iwinner=pan_duan(board,&p1); if(1==iwinner) { printf("computer winner!\n"); break; } if(count>=225) { break; } p2=ai(board,BLACK,comp,user); board[p2.row][p2.col]=p2.player; count++; iwinner=pan_duan(board,&p2); print_board(board); if(1==iwinner) { printf("you winner!\n"); break; } printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); printf("step.player.conputer=%d\n",(int)p2.player); printf("step.row=%d\n",(int)p2.row); printf("step.col=%d\n",(int)p2.col); printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); printf("step.player.user=%d\n",(int)p1.player); printf("step.row=%d\n",(int)p1.row); printf("step.col=%d\n",(int)p1.col); } return 0; }
void player_dialog_init(PlayerDialog *pd, PIECE player) { GtkWidget *vbox, *hbox, *fbox, *w; GSList *group = NULL; int i, i_max; const char *label; pd->player = players + player; vbox = gtk_vbox_new(FALSE, 4); /* Controller combo box */ hbox = gtk_hbox_new(FALSE, 0); w = gtk_label_new("Controller:"); gtk_box_pack_start(GTK_BOX(hbox), w, FALSE, FALSE, 8); w = gtk_combo_box_new_text(); i_max = number_of_ais(); for (i = 0; i < i_max; i++) { AI *a = ai(i); label = "Human"; if (a->func) label = player_to_string(i); gtk_combo_box_append_text(GTK_COMBO_BOX(w), label); } gtk_combo_box_set_active(GTK_COMBO_BOX(w), 0); pd->combo = w; gtk_box_pack_start(GTK_BOX(hbox), w, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0); /* Search box frame */ w = gtk_frame_new("Search"); gtk_box_pack_start(GTK_BOX(vbox), w, FALSE, FALSE, 4); fbox = gtk_vbox_new(FALSE, 4); gtk_container_add(GTK_CONTAINER(w), fbox); gtk_container_border_width(GTK_CONTAINER(fbox), 8); /* Search radio buttons */ for (i = 0; i < SEARCHES; i++) { w = gtk_radio_button_new_with_label(group, search_to_string(i)); group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(w)); gtk_box_pack_start(GTK_BOX(fbox), w, FALSE, FALSE, 0); pd->search[i] = w; } /* Cache toggle button */ pd->cache = gtk_check_button_new_with_label("Use search cache"); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(pd->cache), TRUE); gtk_box_pack_start(GTK_BOX(fbox), pd->cache, FALSE, FALSE, 0); /* Threat-space search toggle button */ pd->tss = gtk_check_button_new_with_label("Threat-space search"); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(pd->tss), FALSE); /*gtk_box_pack_start(GTK_BOX(fbox), pd->tss, FALSE, FALSE, 0);*/ /* Search depth spin button */ w = labeled_spin_new("Depth in moves:", 1., MAX_DEPTH, 1., &pd->depth, NULL); gtk_box_pack_start(GTK_BOX(fbox), w, FALSE, FALSE, 0); /* Minimum branching factor spin button */ w = labeled_spin_new("Minimum branches:", 0., MAX_BRANCH, 2., &pd->branch, NULL); gtk_box_pack_start(GTK_BOX(fbox), w, FALSE, FALSE, 0); /* Ok button */ hbox = gtk_hbox_new(TRUE, 0); w = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(hbox), w, FALSE, FALSE, 0); w = gtk_button_new_from_stock(GTK_STOCK_OK); g_signal_connect(G_OBJECT(w), "clicked", G_CALLBACK(player_dialog_ok), pd); gtk_box_pack_start(GTK_BOX(hbox), w, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0); /* Create dialog window */ pd->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(pd->window), "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), NULL); label = "Mark Player"; if (player) label = va("%s Player", piece_to_string(player)); gtk_window_set_title(GTK_WINDOW(pd->window), label); gtk_window_set_transient_for(GTK_WINDOW(pd->window), GTK_WINDOW(window)); gtk_window_set_modal(GTK_WINDOW(pd->window), TRUE); gtk_window_set_resizable(GTK_WINDOW(pd->window), FALSE); gtk_container_add(GTK_CONTAINER(pd->window), vbox); gtk_container_border_width(GTK_CONTAINER(pd->window), 12); }
void AP_UnixDialog_Paragraph::runModal(XAP_Frame * pFrame) { m_pFrame = pFrame; // Build the window's widgets and arrange them GtkWidget * mainWindow = _constructWindow(); UT_ASSERT(mainWindow); // Populate the window's data items _populateWindowData(); // Attach signals (after data settings, so we don't trigger // updates yet) _connectCallbackSignals(); // Show the top level dialog, gtk_widget_show(mainWindow); #if defined(EMBEDDED_TARGET) && EMBEDDED_TARGET == EMBEDDED_TARGET_HILDON #else // *** this is how we add the gc *** { // attach a new graphics context to the drawing area UT_ASSERT(m_drawingareaPreview && gtk_widget_get_window(m_drawingareaPreview)); // make a new Unix GC GR_UnixCairoAllocInfo ai(m_drawingareaPreview); m_unixGraphics = (GR_CairoGraphics*) XAP_App::getApp()->newGraphics(ai); // let the widget materialize GtkAllocation allocation; gtk_widget_get_allocation(m_drawingareaPreview, &allocation); _createPreviewFromGC(m_unixGraphics, (UT_uint32) allocation.width, (UT_uint32) allocation.height); } // sync all controls once to get started // HACK: the first arg gets ignored _syncControls(id_MENU_ALIGNMENT, true); #endif bool tabs; do { switch(abiRunModalDialog(GTK_DIALOG(mainWindow), pFrame, this, BUTTON_CANCEL, false)) { case BUTTON_OK: event_OK(); tabs = false; break; case BUTTON_TABS: event_Tabs (); tabs = true; break; default: event_Cancel(); tabs = false; break; } } while (tabs); abiDestroyWidget(mainWindow); }
u32 CALifeSmartTerrainTask::level_vertex_id () const { VERIFY3 (ai().game_graph().valid_vertex_id(patrol_point().game_vertex_id()),*m_patrol_path_name,*m_patrol_point->name()); return (patrol_point().level_vertex_id()); }
float CGraphPointType0::ffGetValue() { return (ai().game_graph().vertex(ef_storage().alife().member_item()->m_tGraphID)->vertex_type()[0]); }
void XAP_UnixDialog_FontChooser::runModal(XAP_Frame * pFrame) { m_pFrame = static_cast<XAP_Frame *>(pFrame); // used similarly to convert between text and numeric arguments static char sizeString[50]; // build the dialog GtkWidget * cf = constructWindow(); // freeze updates of the preview m_blockUpdate = true; // to sort out dupes std::set<std::string> fontSet; GtkTreeModel* model; GtkTreeIter iter; model = gtk_tree_view_get_model(GTK_TREE_VIEW(m_fontList)); gtk_list_store_clear(GTK_LIST_STORE(model)); GR_GraphicsFactory * pGF = XAP_App::getApp()->getGraphicsFactory(); if(!pGF) { return; } const std::vector<std::string> & names = GR_CairoGraphics::getAllFontNames(); for (std::vector<std::string>::const_iterator i = names.begin(); i != names.end(); ++i) { const std::string & fName = *i; if (fontSet.find(fName) == fontSet.end()) { fontSet.insert(fName); gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set(GTK_LIST_STORE(model), &iter, TEXT_COLUMN, fName.c_str(), -1); } } // Set the defaults in the list boxes according to dialog data gint foundAt = 0; const std::string sFontFamily = getVal("font-family"); foundAt = searchTreeView(GTK_TREE_VIEW(m_fontList), sFontFamily.c_str()); // select and scroll to font name if (foundAt >= 0) { GtkTreePath* path = gtk_tree_path_new_from_indices(foundAt, -1); gtk_tree_view_set_cursor(GTK_TREE_VIEW(m_fontList), path, NULL, FALSE); gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(m_fontList), path, NULL, TRUE, 0.5 , 0.0); gtk_tree_path_free(path); } // this is pretty messy listStyle st = LIST_STYLE_NORMAL; const std::string sWeight = getVal("font-weight"); const std::string sStyle = getVal("font-style"); if (sStyle.empty() || sWeight.empty()) st = LIST_STYLE_NONE; else { bool isBold = !g_ascii_strcasecmp(sWeight.c_str(), "bold"); bool isItalic = !g_ascii_strcasecmp(sStyle.c_str(), "italic"); if (!isBold && !isItalic) { st = LIST_STYLE_NORMAL; } else if (!isItalic && isBold) { st = LIST_STYLE_BOLD; } else if (isItalic && !isBold) { st = LIST_STYLE_ITALIC; } else if (isItalic && isBold) { st = LIST_STYLE_BOLD_ITALIC; } else { UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN); } } // select and scroll to style name if (st != LIST_STYLE_NONE) { GtkTreePath* path = gtk_tree_path_new_from_indices(st, -1); gtk_tree_view_set_cursor(GTK_TREE_VIEW(m_styleList), path, NULL, FALSE); gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(m_styleList), path, NULL, TRUE, 0.5 , 0.0); gtk_tree_path_free(path); } g_snprintf(sizeString, 60, "%s", std_size_string(UT_convertToPoints(getVal("font-size").c_str()))); foundAt = searchTreeView(GTK_TREE_VIEW(m_sizeList), XAP_EncodingManager::fontsizes_mapping.lookupBySource(sizeString)); // select and scroll to size name if (foundAt >= 0) { GtkTreePath* path = gtk_tree_path_new_from_indices(foundAt, -1); gtk_tree_view_set_cursor(GTK_TREE_VIEW(m_sizeList), path, NULL, FALSE); gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(m_sizeList), path, NULL, TRUE, 0.5 , 0.0); gtk_tree_path_free(path); } // Set color in the color selector const std::string sColor = getVal("color"); if (!sColor.empty()) { UT_RGBColor c; UT_parseColor(sColor.c_str(), c); GdkRGBA *color = UT_UnixRGBColorToGdkRGBA(c); m_currentFGColor = *color; gdk_rgba_free(color); gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(m_colorSelector), &m_currentFGColor); } else { // if we have no color, use a placeholder of funky values // the user can't pick interactively. This catches ALL // the cases except where the user specifically enters -1 for // all Red, Green and Blue attributes manually. This user // should expect it not to touch the color. :) gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(m_colorSelector), &m_funkyColor); } // Set color in the color selector const std::string sBGCol = getVal("bgcolor"); if (!sBGCol.empty() && strcmp(sBGCol.c_str(),"transparent") != 0) { UT_RGBColor c; UT_parseColor(sBGCol.c_str(), c); GdkRGBA *color = UT_UnixRGBColorToGdkRGBA(c); m_currentBGColor = *color; gdk_rgba_free(color); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkTransparency), FALSE); gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(m_bgcolorSelector), &m_currentBGColor); } else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkTransparency), TRUE); // fix for GTK's questionable gtk_toggle_set_active behaviour (emits when setting TRUE) m_bChangedStrikeOut = m_bStrikeout; m_bChangedUnderline = m_bUnderline; m_bChangedOverline = m_bOverline; m_bChangedHidden = m_bHidden; m_bChangedSubScript = m_bSubScript; m_bChangedSuperScript = m_bSuperScript; // set the strikeout, underline, overline, and hidden check buttons gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkStrikeOut), m_bStrikeout); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkUnderline), m_bUnderline); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkOverline), m_bOverline); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkHidden), m_bHidden); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkSubScript), m_bSubScript); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_checkSuperScript), m_bSuperScript); m_doneFirstFont = true; // attach a new graphics context gtk_widget_show ( cf ) ; GR_UnixCairoAllocInfo ai(m_preview); m_gc = (GR_CairoGraphics*) XAP_App::getApp()->newGraphics(ai); GtkAllocation alloc; gtk_widget_get_allocation(m_preview, &alloc); _createFontPreviewFromGC(m_gc,alloc.width,alloc.height); // // This enables callbacks on the preview area with a widget pointer to // access this dialog. // g_object_set_data(G_OBJECT(m_preview), "user-data", this); // unfreeze updates of the preview m_blockUpdate = false; // manually trigger an update updatePreview(); switch ( abiRunModalDialog ( GTK_DIALOG(cf), pFrame, this, BUTTON_CANCEL, true ) ) { case BUTTON_OK: { m_answer = a_OK; break ; } default: { m_answer = a_CANCEL; break; } } // these dialogs are cached around through the dialog framework, // and this variable needs to get set back m_doneFirstFont = false; UT_DEBUGMSG(("FontChooserEnd: Family[%s%s] Size[%s%s] Weight[%s%s] Style[%s%s] Color[%s%s] Underline[%d%s] StrikeOut[%d%s] SubScript[%d%s] SuperScript[%d%s]\n", getVal("font-family").c_str(), ((m_bChangedFontFamily) ? "(chg)" : ""), getVal("font-size").c_str(), ((m_bChangedFontSize) ? "(chg)" : ""), getVal("font-weight").c_str(), ((m_bChangedFontWeight) ? "(chg)" : ""), getVal("font-style").c_str(), ((m_bChangedFontStyle) ? "(chg)" : ""), getVal("color").c_str(), ((m_bChangedColor) ? "(chg)" : ""), m_bUnderline, ((m_bChangedUnderline) ? "(chg)" : ""), m_bStrikeout, ((m_bChangedStrikeOut) ? "(chg)" : ""), m_bSubScript, ((m_bChangedSubScript) ? "(chg)" : ""), m_bSuperScript, ((m_bChangedSuperScript) ? "(chg)" : "") )); // answer should be set by the appropriate callback // the caller can get the answer from getAnswer(). m_pFrame = NULL; }
void CLevelGraph::draw_covers () { float half_size = ai().level_graph().header().cell_size()*.5f; xr_vector<CCoverPoint*> nearest; nearest.reserve (1000); ai().cover_manager().covers().nearest(Device.vCameraPosition,5.f,nearest); xr_vector<CCoverPoint*>::const_iterator I = nearest.begin(); xr_vector<CCoverPoint*>::const_iterator E = nearest.end(); for ( ; I != E; ++I) { Fvector position = (*I)->position(); position.y += 1.5f; Level().debug_renderer().draw_aabb (position,half_size - .01f,1.f,ai().level_graph().header().cell_size()*.5f-.01f,D3DCOLOR_XRGB(0*255,255,0*255)); CVertex *v = vertex((*I)->level_vertex_id()); Fvector direction; float best_value = -1.f; for (u32 i=0, j = 0; i<36; ++i) { float value = high_cover_in_direction(float(10*i)/180.f*PI,v); direction.setHP (float(10*i)/180.f*PI,0); direction.normalize (); direction.mul (value*half_size); direction.add (position); direction.y = position.y; Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(0,0,255)); value = compute_high_square(float(10*i)/180.f*PI,PI/2.f,v); if (value > best_value) { best_value = value; j = i; } } direction.set (position.x - half_size*float(v->high_cover(0))/15.f,position.y,position.z); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); direction.set (position.x,position.y,position.z + half_size*float(v->high_cover(1))/15.f); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); direction.set (position.x + half_size*float(v->high_cover(2))/15.f,position.y,position.z); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); direction.set (position.x,position.y,position.z - half_size*float(v->high_cover(3))/15.f); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); float value = high_cover_in_direction(float(10*j)/180.f*PI,v); direction.setHP (float(10*j)/180.f*PI,0); direction.normalize (); direction.mul (value*half_size); direction.add (position); direction.y = position.y; Level().debug_renderer().draw_line (Fidentity,position,direction,D3DCOLOR_XRGB(0,0,0)); // low { position = (*I)->position(); position.y += 0.6f; Level().debug_renderer().draw_aabb (position,half_size - .01f,1.f,ai().level_graph().header().cell_size()*.5f-.01f,D3DCOLOR_XRGB(0*255,255,0*255)); CVertex *v = vertex((*I)->level_vertex_id()); Fvector direction; float best_value = -1.f; for (u32 i=0, j = 0; i<36; ++i) { float value = low_cover_in_direction(float(10*i)/180.f*PI,v); direction.setHP (float(10*i)/180.f*PI,0); direction.normalize (); direction.mul (value*half_size); direction.add (position); direction.y = position.y; Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(0,0,255)); value = compute_low_square(float(10*i)/180.f*PI,PI/2.f,v); if (value > best_value) { best_value = value; j = i; } } direction.set (position.x - half_size*float(v->low_cover(0))/15.f,position.y,position.z); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); direction.set (position.x,position.y,position.z + half_size*float(v->low_cover(1))/15.f); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); direction.set (position.x + half_size*float(v->low_cover(2))/15.f,position.y,position.z); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); direction.set (position.x,position.y,position.z - half_size*float(v->low_cover(3))/15.f); Level().debug_renderer().draw_line(Fidentity,position,direction,D3DCOLOR_XRGB(255,0,0)); float value = low_cover_in_direction(float(10*j)/180.f*PI,v); direction.setHP (float(10*j)/180.f*PI,0); direction.normalize (); direction.mul (value*half_size); direction.add (position); direction.y = position.y; Level().debug_renderer().draw_line (Fidentity,position,direction,D3DCOLOR_XRGB(0,0,0)); } } }
//============================================================================= // Call repeatedly by the main message loop in WinMain //============================================================================= void Game::run(HWND hwnd) { if(graphics == NULL) // if graphics not initialized return; // calculate elapsed time of last frame, save in frameTime QueryPerformanceCounter(&timeEnd); frameTime = (float)(timeEnd.QuadPart - timeStart.QuadPart ) / (float)timerFreq.QuadPart; // Power saving code, requires winmm.lib // if not enough time has elapsed for desired frame rate if (frameTime < MIN_FRAME_TIME) { sleepTime = (DWORD)((MIN_FRAME_TIME - frameTime)*1000); timeBeginPeriod(1); // Request 1mS resolution for windows timer Sleep(sleepTime); // release cpu for sleepTime timeEndPeriod(1); // End 1mS timer resolution return; } if (frameTime > 0.0) fps = (fps*0.99f) + (0.01f/frameTime); // average fps if (frameTime > MAX_FRAME_TIME) // if frame rate is very slow frameTime = MAX_FRAME_TIME; // limit maximum frameTime timeStart = timeEnd; // update(), ai(), and collisions() are pure virtual functions. // These functions must be provided in the class that inherits from Game. if (!paused) // if not paused { update(); // update all game items ai(); // artificial intelligence collisions(); // handle collisions input->vibrateControllers(frameTime); // handle controller vibration } renderGame(); // draw all game items //check for console key if (input->wasKeyPressed(CONSOLE_KEY)) { console->showHide(); paused = console->getVisible(); // pause game when console is visible } consoleCommand(); // process user entered console command input->readControllers(); // read state of controllers messageDialog->update(); inputDialog->update(); audio->run(); // perform periodic sound engine tasks // if Alt+Enter toggle fullscreen/window if (input->isKeyDown(ALT_KEY) && input->wasKeyPressed(ENTER_KEY)) setDisplayMode(graphicsNS::TOGGLE); // toggle fullscreen/window // if Esc key, set window mode if (input->isKeyDown(ESC_KEY)) setDisplayMode(graphicsNS::WINDOW); // set window mode // Clear input // Call this after all key checks are done input->clear(inputNS::KEYS_PRESSED); }
void CScriptEntity::ProcessScripts() { CScriptEntityAction *l_tpEntityAction = 0; #ifdef DEBUG bool empty_queue = m_tpActionQueue.empty(); #endif while (!m_tpActionQueue.empty()) { l_tpEntityAction= m_tpActionQueue.front(); VERIFY (l_tpEntityAction); #ifdef _DEBUG // if (!xr_strcmp("m_stalker_wounded",*object().cName())) // Msg ("%6d Processing action : %s",Device.dwTimeGlobal,*l_tpEntityAction->m_tAnimationAction.m_caAnimationToPlay); #endif if (m_tpCurrentEntityAction != l_tpEntityAction) l_tpEntityAction->initialize (); m_tpCurrentEntityAction = l_tpEntityAction; if (!l_tpEntityAction->CheckIfActionCompleted()) break; #ifdef _DEBUG // if (!xr_strcmp("m_stalker_wounded",*object().cName())) // Msg ("%6d Action completed : %s",Device.dwTimeGlobal,*l_tpEntityAction->m_tAnimationAction.m_caAnimationToPlay); #endif vfFinishAction(l_tpEntityAction); #ifdef DEBUG if (psAI_Flags.is(aiLua)) Msg("Entity Action removed!!!"); #endif if (true /*psAI_Flags.is(aiLua)*/ ) { object().callback(GameObject::eActionTypeRemoved)(object().lua_game_object(),u32(eActionTypeRemoved)); } xr_delete (l_tpEntityAction); m_tpActionQueue.erase(m_tpActionQueue.begin()); } if (m_tpActionQueue.empty()) { #ifdef DEBUG if (empty_queue) ai().script_engine().script_log (ScriptStorage::eLuaMessageTypeInfo,"Object %s has an empty script queue!",*object().cName()); #endif return; } try { bool l_bCompleted; l_bCompleted = l_tpEntityAction->m_tWatchAction.m_bCompleted; bfAssignWatch (l_tpEntityAction); if (l_tpEntityAction->m_tWatchAction.m_bCompleted && !l_bCompleted) object().callback(GameObject::eActionTypeWatch)(object().lua_game_object(),u32(eActionTypeWatch)); l_bCompleted = l_tpEntityAction->m_tAnimationAction.m_bCompleted; bfAssignAnimation(l_tpEntityAction); l_bCompleted = l_tpEntityAction->m_tSoundAction.m_bCompleted; bfAssignSound (l_tpEntityAction); if (l_tpEntityAction->m_tSoundAction.m_bCompleted && !l_bCompleted) object().callback(GameObject::eActionTypeSound)(object().lua_game_object(),u32(eActionTypeSound)); l_bCompleted = l_tpEntityAction->m_tParticleAction.m_bCompleted; bfAssignParticles(l_tpEntityAction); if (l_tpEntityAction->m_tParticleAction.m_bCompleted && !l_bCompleted) object().callback(GameObject::eActionTypeParticle)(object().lua_game_object(),u32(eActionTypeParticle)); l_bCompleted = l_tpEntityAction->m_tObjectAction.m_bCompleted; bfAssignObject (l_tpEntityAction); if (l_tpEntityAction->m_tObjectAction.m_bCompleted && !l_bCompleted) object().callback(GameObject::eActionTypeObject)(object().lua_game_object(),u32(eActionTypeObject)); l_bCompleted = l_tpEntityAction->m_tMovementAction.m_bCompleted; bfAssignMovement(l_tpEntityAction); if (l_tpEntityAction->m_tMovementAction.m_bCompleted && !l_bCompleted) object().callback(GameObject::eActionTypeMovement)(object().lua_game_object(),u32(eActionTypeMovement), -1); // ”становить выбранную анимацию if (!l_tpEntityAction->m_tAnimationAction.m_bCompleted) bfScriptAnimation (); bfAssignMonsterAction(l_tpEntityAction); } catch(...) { ResetScriptData (); } }
void game_sv_GameState::Create (shared_str &options) { string_path fn_game; m_item_respawner.clear_respawns(); if (FS.exist(fn_game, "$level$", "level.game")) { IReader *F = FS.r_open (fn_game); IReader *O = 0; // Load RPoints if (0!=(O = F->open_chunk (RPOINT_CHUNK))) { for (int id=0; O->find_chunk(id); ++id) { RPoint R; u8 team; u8 type; u16 GameType; shared_str rp_profile; O->r_fvector3 (R.P); O->r_fvector3 (R.A); team = O->r_u8 (); type = O->r_u8 (); GameType = O->r_u16 (); if(type==rptItemSpawn) O->r_stringZ (rp_profile); if (GameType != EGameIDs(u16(-1))) { if ((Type() == eGameIDCaptureTheArtefact) && (GameType & eGameIDCaptureTheArtefact)) { team = team - 1; R_ASSERT2( ((team >= 0) && (team < 4)) || (type != rptActorSpawn), "Problem with CTA Team indexes. Propably you have added rpoint of team 0 for cta game type."); } if ((!(GameType & eGameIDDeathmatch) && (Type() == eGameIDDeathmatch)) || (!(GameType & eGameIDTeamDeathmatch) && (Type() == eGameIDTeamDeathmatch)) || (!(GameType & eGameIDArtefactHunt) && (Type() == eGameIDArtefactHunt)) || (!(GameType & eGameIDCaptureTheArtefact) && (Type() == eGameIDCaptureTheArtefact)) ) { continue; }; }; switch (type) { case rptActorSpawn: { rpoints[team].push_back (R); for (int i=0; i<int(rpoints[team].size())-1; i++) { RPoint rp = rpoints[team][i]; float dist = R.P.distance_to_xz(rp.P)/2; if (dist<rpoints_MinDist[team]) rpoints_MinDist[team] = dist; dist = R.P.distance_to(rp.P)/2; if (dist<rpoints_Dist[team]) rpoints_Dist[team] = dist; }; }break; case rptItemSpawn: { m_item_respawner.add_new_rpoint(rp_profile, R); } }; }; O->close(); } FS.r_close (F); } if (!g_dedicated_server) { // loading scripts ai().script_engine().remove_script_process(ScriptEngine::eScriptProcessorGame); string_path S; FS.update_path (S,"$game_config$","script.ltx"); CInifile *l_tpIniFile = xr_new<CInifile>(S); R_ASSERT (l_tpIniFile); if( l_tpIniFile->section_exist( type_name() ) ) if (l_tpIniFile->r_string(type_name(),"script")) ai().script_engine().add_script_process(ScriptEngine::eScriptProcessorGame,xr_new<CScriptProcess>("game",l_tpIniFile->r_string(type_name(),"script"))); else ai().script_engine().add_script_process(ScriptEngine::eScriptProcessorGame,xr_new<CScriptProcess>("game","")); xr_delete (l_tpIniFile); } //--------------------------------------------------------------------- ConsoleCommands_Create(); //--------------------------------------------------------------------- // CCC_LoadCFG_custom* pTmp = xr_new<CCC_LoadCFG_custom>("sv_"); // pTmp->Execute (Console->ConfigFile); // xr_delete (pTmp); //--------------------------------------------------------------------- LPCSTR svcfg_ltx_name = "-svcfg "; if (strstr(Core.Params, svcfg_ltx_name)) { string_path svcfg_name = ""; int sz = xr_strlen(svcfg_ltx_name); sscanf (strstr(Core.Params,svcfg_ltx_name)+sz,"%[^ ] ",svcfg_name); // if (FS.exist(svcfg_name)) { Console->ExecuteScript(svcfg_name); } }; //--------------------------------------------------------------------- ReadOptions(options); }
void CSE_ALifeGroupAbstract::try_switch_offline () { // checking if group is not empty if (m_tpMembers.empty()) return; // so, we have a group of objects // therefore check all the group members if they are ready to switch offline CSE_ALifeDynamicObject *I = smart_cast<CSE_ALifeDynamicObject*>(base()); VERIFY (I); // iterating on group members u32 i = 0; u32 N = (u32)m_tpMembers.size(); for (; i<N; ++i) { // casting group member to the abstract monster to get access to the Health property CSE_ALifeMonsterAbstract *tpGroupMember = smart_cast<CSE_ALifeMonsterAbstract*>(ai().alife().objects().object(m_tpMembers[i])); if (!tpGroupMember) continue; // check if monster is not dead if (tpGroupMember->g_Alive()) { // so, monster is not dead // checking if the object is _not_ ready to switch offline if (!tpGroupMember->can_switch_offline()) continue; if (!tpGroupMember->can_switch_online()) // so, it is not ready, breaking a cycle, because we can't // switch group offline since not all the group members are ready // to switch offline break; if (I->alife().graph().actor()->o_Position.distance_to(tpGroupMember->o_Position) <= I->alife().offline_distance()) // so, it is not ready, breaking a cycle, because we can't // switch group offline since not all the group members are ready // to switch offline break; continue; } // detach object from the group tpGroupMember->fHealth = 0.f; tpGroupMember->m_bDirectControl = true; m_tpMembers.erase (m_tpMembers.begin() + i); tpGroupMember->m_bOnline = false; CSE_ALifeInventoryItem *item = smart_cast<CSE_ALifeInventoryItem*>(tpGroupMember); if (item && item->attached()) { CSE_ALifeDynamicObject *object = ai().alife().objects().object(tpGroupMember->ID_Parent,true); if (object) object->detach (item); } // store the __new separate object into the registries I->alife().register_object (tpGroupMember); // and remove it from the graph point but do not remove it from the current level map CSE_ALifeInventoryItem *l_tpALifeInventoryItem = smart_cast<CSE_ALifeInventoryItem*>(tpGroupMember); if (!l_tpALifeInventoryItem || !l_tpALifeInventoryItem->attached()) I->alife().graph().remove (tpGroupMember,tpGroupMember->m_tGraphID,false); tpGroupMember->m_bOnline = true; --m_wCount; --i; --N; } // checking if group is not empty if (m_tpMembers.empty()) return; if (!I->can_switch_offline()) return; if (I->can_switch_online() || (i == N)) I->alife().switch_offline (I); }
void Enemy::idle_update(void) //start move { if(target) ai(); }
void CLevel::OnFrame () { #ifdef DEBUG_MEMORY_MANAGER debug_memory_guard __guard__; #endif // DEBUG_MEMORY_MANAGER #ifdef DEBUG DBG_RenderUpdate( ); #endif // #ifdef DEBUG Fvector temp_vector; m_feel_deny.feel_touch_update (temp_vector, 0.f); if (GameID()!=eGameIDSingle) psDeviceFlags.set(rsDisableObjectsAsCrows,true); else psDeviceFlags.set(rsDisableObjectsAsCrows,false); // commit events from bullet manager from prev-frame Device.Statistic->TEST0.Begin (); BulletManager().CommitEvents (); Device.Statistic->TEST0.End (); // Client receive if (net_isDisconnected()) { if (OnClient() && GameID() != eGameIDSingle) { #ifdef DEBUG Msg("* I'm disconnected, so clear all objects..."); #endif // #ifdef DEBUG ClearAllObjects(); } Engine.Event.Defer ("kernel:disconnect"); return; } else { Device.Statistic->netClient1.Begin(); ClientReceive (); Device.Statistic->netClient1.End (); } ProcessGameEvents (); if (m_bNeed_CrPr) make_NetCorrectionPrediction(); if(!g_dedicated_server ) { if (g_mt_config.test(mtMap)) Device.seqParallel.push_back (fastdelegate::FastDelegate0<>(m_map_manager,&CMapManager::Update)); else MapManager().Update (); if( IsGameTypeSingle() && Device.dwPrecacheFrame==0 ) { if (g_mt_config.test(mtMap)) Device.seqParallel.push_back (fastdelegate::FastDelegate0<>(m_game_task_manager,&CGameTaskManager::UpdateTasks)); else GameTaskManager().UpdateTasks(); } } // Inherited update inherited::OnFrame (); // Draw client/server stats if ( !g_dedicated_server && psDeviceFlags.test(rsStatistic)) { CGameFont* F = HUD().Font().pFontDI; if (!psNET_direct_connect) { if ( IsServer() ) { const IServerStatistic* S = Server->GetStatistic(); F->SetHeightI (0.015f); F->OutSetI (0.0f,0.5f); F->SetColor (D3DCOLOR_XRGB(0,255,0)); F->OutNext ("IN: %4d/%4d (%2.1f%%)", S->bytes_in_real, S->bytes_in, 100.f*float(S->bytes_in_real)/float(S->bytes_in)); F->OutNext ("OUT: %4d/%4d (%2.1f%%)", S->bytes_out_real, S->bytes_out, 100.f*float(S->bytes_out_real)/float(S->bytes_out)); F->OutNext ("client_2_sever ping: %d", net_Statistic.getPing()); F->OutNext ("SPS/Sended : %4d/%4d", S->dwBytesPerSec, S->dwBytesSended); F->OutNext ("sv_urate/cl_urate : %4d/%4d", psNET_ServerUpdate, psNET_ClientUpdate); F->SetColor (D3DCOLOR_XRGB(255,255,255)); struct net_stats_functor { xrServer* m_server; CGameFont* F; void operator()(IClient* C) { m_server->UpdateClientStatistic(C); F->OutNext("%10s: P(%d), BPS(%2.1fK), MRR(%2d), MSR(%2d), Retried(%2d), Blocked(%2d)", //Server->game->get_option_s(*C->Name,"name",*C->Name), C->name.c_str(), C->stats.getPing(), float(C->stats.getBPS()),// /1024, C->stats.getMPS_Receive (), C->stats.getMPS_Send (), C->stats.getRetriedCount(), C->stats.dwTimesBlocked ); } }; net_stats_functor tmp_functor; tmp_functor.m_server = Server; tmp_functor.F = F; Server->ForEachClientDo(tmp_functor); } if (IsClient()) { IPureClient::UpdateStatistic(); F->SetHeightI(0.015f); F->OutSetI (0.0f,0.5f); F->SetColor (D3DCOLOR_XRGB(0,255,0)); F->OutNext ("client_2_sever ping: %d", net_Statistic.getPing()); F->OutNext ("sv_urate/cl_urate : %4d/%4d", psNET_ServerUpdate, psNET_ClientUpdate); F->SetColor (D3DCOLOR_XRGB(255,255,255)); F->OutNext("P(%d), BPS(%2.1fK), MRR(%2d), MSR(%2d), Retried(%2d), Blocked(%2d), Sended(%2d), SPS(%2d)", //Server->game->get_option_s(C->Name,"name",C->Name), // C->Name, net_Statistic.getPing(), float(net_Statistic.getBPS()),// /1024, net_Statistic.getMPS_Receive (), net_Statistic.getMPS_Send (), net_Statistic.getRetriedCount(), net_Statistic.dwTimesBlocked, net_Statistic.dwBytesSended, net_Statistic.dwBytesPerSec ); #ifdef DEBUG if (!pStatGraphR) { pStatGraphR = new CStatGraph(); pStatGraphR->SetRect(50, 700, 300, 68, 0xff000000, 0xff000000); //m_stat_graph->SetGrid(0, 0.0f, 10, 1.0f, 0xff808080, 0xffffffff); pStatGraphR->SetMinMax(0.0f, 65536.0f, 1000); pStatGraphR->SetStyle(CStatGraph::stBarLine); pStatGraphR->AppendSubGraph(CStatGraph::stBarLine); } pStatGraphR->AppendItem(float(net_Statistic.getBPS()), 0xff00ff00, 0); F->OutSet(20.f, 700.f); F->OutNext("64 KBS"); #endif } } } else { #ifdef DEBUG if (pStatGraphR) xr_delete(pStatGraphR); #endif } // g_pGamePersistent->Environment().SetGameTime (GetGameDayTimeSec(),GetGameTimeFactor()); g_pGamePersistent->Environment().SetGameTime (GetEnvironmentGameDayTimeSec(),game->GetEnvironmentGameTimeFactor()); //Device.Statistic->cripting.Begin (); if (!g_dedicated_server) ai().script_engine().script_process (ScriptEngine::eScriptProcessorLevel)->update(); //Device.Statistic->Scripting.End (); m_ph_commander->update (); m_ph_commander_scripts->update (); // autosave_manager().update (); //просчитать полет пуль Device.Statistic->TEST0.Begin (); BulletManager().CommitRenderSet (); Device.Statistic->TEST0.End (); // update static sounds if(!g_dedicated_server) { if (g_mt_config.test(mtLevelSounds)) Device.seqParallel.push_back (fastdelegate::FastDelegate0<>(m_level_sound_manager,&CLevelSoundManager::Update)); else m_level_sound_manager->Update (); } // deffer LUA-GC-STEP if (!g_dedicated_server) { if (g_mt_config.test(mtLUA_GC)) Device.seqParallel.push_back (fastdelegate::FastDelegate0<>(this,&CLevel::script_gc)); else script_gc () ; } //----------------------------------------------------- if (pStatGraphR) { static float fRPC_Mult = 10.0f; static float fRPS_Mult = 1.0f; pStatGraphR->AppendItem(float(m_dwRPC)*fRPC_Mult, 0xffff0000, 1); pStatGraphR->AppendItem(float(m_dwRPS)*fRPS_Mult, 0xff00ff00, 0); }; }
// ------------------------------------------------------------------------------------------------- int CUIFactionWarWnd::get_max_member_count() { luabind::functor<int> funct; R_ASSERT( ai().script_engine().functor( "pda.get_max_member_count", funct ) ); return funct(); }
void CLevel::OnRender() { inherited::OnRender (); if (!game) return; Game().OnRender(); //отрисовать трассы пуль //Device.Statistic->TEST1.Begin(); BulletManager().Render(); //Device.Statistic->TEST1.End(); //отрисовать интерфейc пользователя HUD().RenderUI(); #ifdef DEBUG draw_wnds_rects(); ph_world->OnRender (); #endif // DEBUG #ifdef DEBUG if (ai().get_level_graph()) ai().level_graph().render(); #ifdef DEBUG_PRECISE_PATH test_precise_path (); #endif CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(Level().CurrentEntity()); if (stalker) stalker->OnRender (); if (bDebug) { for (u32 I=0; I < Level().Objects.o_count(); I++) { CObject* _O = Level().Objects.o_get_by_iterator(I); CAI_Stalker* stalker = smart_cast<CAI_Stalker*>(_O); if (stalker) stalker->OnRender (); CPhysicObject *physic_object = smart_cast<CPhysicObject*>(_O); if (physic_object) physic_object->OnRender(); CSpaceRestrictor *space_restrictor = smart_cast<CSpaceRestrictor*> (_O); if (space_restrictor) space_restrictor->OnRender(); CClimableObject *climable = smart_cast<CClimableObject*> (_O); if(climable) climable->OnRender(); CTeamBaseZone *team_base_zone = smart_cast<CTeamBaseZone*>(_O); if (team_base_zone) team_base_zone->OnRender(); if (GameID() != eGameIDSingle) { CInventoryItem* pIItem = smart_cast<CInventoryItem*>(_O); if (pIItem) pIItem->OnRender(); } if (dbg_net_Draw_Flags.test(dbg_draw_skeleton)) //draw skeleton { CGameObject* pGO = smart_cast<CGameObject*> (_O); if (pGO && pGO != Level().CurrentViewEntity() && !pGO->H_Parent()) { if (pGO->Position().distance_to_sqr(Device.vCameraPosition) < 400.0f) { pGO->dbg_DrawSkeleton(); } } }; } // [7/5/2005] if (Server && Server->game) Server->game->OnRender(); // [7/5/2005] ObjectSpace.dbgRender (); //--------------------------------------------------------------------- HUD().Font().pFontStat->OutSet (170,630); HUD().Font().pFontStat->SetHeight (16.0f); HUD().Font().pFontStat->SetColor (0xffff0000); if(Server)HUD().Font().pFontStat->OutNext ("Client Objects: [%d]",Server->GetEntitiesNum()); HUD().Font().pFontStat->OutNext ("Server Objects: [%d]",Objects.o_count()); HUD().Font().pFontStat->OutNext ("Interpolation Steps: [%d]", Level().GetInterpolationSteps()); HUD().Font().pFontStat->SetHeight (8.0f); //--------------------------------------------------------------------- } #endif #ifdef DEBUG if (bDebug) { DBG().draw_object_info (); DBG().draw_text (); DBG().draw_level_info (); } debug_renderer().render (); DBG().draw_debug_text(); if (psAI_Flags.is(aiVision)) { for (u32 I=0; I < Level().Objects.o_count(); I++) { CObject *object = Objects.o_get_by_iterator(I); CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(object); if (!stalker) continue; stalker->dbg_draw_vision (); } } if (psAI_Flags.test(aiDrawVisibilityRays)) { for (u32 I=0; I < Level().Objects.o_count(); I++) { CObject *object = Objects.o_get_by_iterator(I); CAI_Stalker *stalker = smart_cast<CAI_Stalker*>(object); if (!stalker) continue; stalker->dbg_draw_visibility_rays (); } } #endif }
float CUIFactionWarWnd::get_max_power() { luabind::functor<float> funct; R_ASSERT( ai().script_engine().functor( "pda.get_max_power", funct ) ); return funct(); }
void CALifeMonsterDetailPathManager::target (const GameGraph::_GRAPH_ID &game_vertex_id) { VERIFY (ai().game_graph().valid_vertex_id(game_vertex_id)); target (game_vertex_id,ai().game_graph().vertex(game_vertex_id)->level_vertex_id(),ai().game_graph().vertex(game_vertex_id)->level_point()); }
IC Fvector construct_position (u32 level_vertex_id, float x, float z) { return (Fvector().set(x,ai().level_graph().vertex_plane_y(level_vertex_id,x,z),z)); }