コード例 #1
0
int ClusterReceiver::svc(void)
{
	char buf[U_SIZE] = { };

	while(loop)
	{
		memset(buf,0,U_SIZE);
		ACE_INET_Addr remote_addr;
		int rece_size = 0;
		ACE_Time_Value tv(1.5);
		//check reload
		if(reload)
		{
			//close orign channel
			switch(recv_type_)
			{
				case MCAST:
					mcast_.leave(addr_);
					mcast_.close();
					addr_.dump();
					break;
				case UCAST:
					ucast_.close();
			}

			//join new channel
			InitChannel();

			reload = false;
		}

		switch(recv_type_)
		{
			case MCAST:
				{
					rece_size = mcast_.recv((void*)buf,U_SIZE,remote_addr,0,&tv);
				}
				break;
			case UCAST:
				{
					rece_size = ucast_.recv((void*)buf,U_SIZE,remote_addr,0,&tv);
				}
				break;
		}
		if(rece_size && (*buf))
		{
			mongo::BSONObj temp((char*)buf);
			std::cout << temp << std::endl;
			std::vector<mongo::BSONElement> ele;
			temp.elems(ele);

			if(ele.size()<3)
			{
				LOG4CXX_WARN(log_,"Too little BSONObj fields");
			}
			else if(!temp.hasField("host_ID") || !temp.hasField("heartbeat"))
			{
				LOG4CXX_WARN(log_,"This BSONObj do not hace necessary fields!");
			}
			else
			{
				char* ch = new char[temp.objsize()];
				memcpy(ch,buf,temp.objsize());
				msg_ = new ACE_Message_Block(ch,temp.objsize());
				sender_->Put(msg_);
			}
		}
	}

	return 0;
}
コード例 #2
0
ファイル: type-ops.cpp プロジェクト: fredemmott/hhvm
Type typeToInt(Type ty) {
  if (auto const v = tv(ty)) return ival(cellToInt(*v));
  if (ty.subtypeOf(TNull))   return ival(0);
  return TInt;
}
コード例 #3
0
ファイル: device.cpp プロジェクト: nykma/ykt4sungard
int KSGDevice::ExecuteTask(DeviceNodeType* node,Task* task)
{
	// 检查是否支持指令
	bool free_conn = false;
	DI devintr = FindDevInterface(task->GetTaskCode());
	if(!devintr)
	{
		ACE_DEBUG((LM_ERROR,"设备不支持该指令..."));
		throw TaskNotSupportedException();
	}
	//
	int ret;
	ACE_HANDLE handler;
	ret = find_handler(node,&handler);
	if(ret)
	{
		ACE_DEBUG((LM_ERROR,"连接指定设备失败!"));
		return TASK_ERR_CONNECT;
	}
	// 执行指令
	try
	{
		task->_handle = handler;
		ret = devintr->ExecuteTask(node,task);
	}
	catch(...)
	{
		// ignore
	}
	// 如果指令执行不成功
	if(ret != TASK_SUCCESS)
	{
		//
		if(node->connect_module() == KSGDeviceNode::cm_short_conn)
		{
			free_conn = true;
		}
		else
		{
			if(ret == TASK_INVALID_CONN)
				free_conn = true;
			else
			{
				ACE_Time_Value tv(1);
				int res = ACE::handle_exception_ready(task->_handle,&tv);
				if(res >0)
				{
					// 如果发生异常,则重连
					free_conn = true;
				}
				else if(res == 0) // 超时
				{
					free_conn = true;
				}
				else // 返回错误
				{

				}
			}
		}
	}
	
	try
	{
		if(release_handler(node,&handler,free_conn))
		{
			ACE_DEBUG((LM_ERROR,"释放连接失败"));
		}
		else
		{
			// 如果关闭连接,需要等待 500
			if(free_conn)
				KSGThreadUtil::Sleep(500);
		}
	}
	catch (...)
	{
		ACE_DEBUG((LM_ERROR,"关闭连接异常!"));
	}
	return ret;
}
コード例 #4
0
ファイル: Hrefine3D.cpp プロジェクト: Chang-Liu-0520/nodal-dg
//---------------------------------------------------------
void NDG3D::Hrefine3D(IVec& refineflag)
//---------------------------------------------------------
{
  DVec lVX("lVX"), lVY("lVY"), lVZ("lVZ");

  int a=1, b=2, c=3, d=4, e=5, 
      f=6, g=7, h=8, i=9, j=10;

  //             a b c d  e    f    g    h    i    j
  lVX.load(10, " 0 1 0 0  0.5  0.5  0.0  0.0  0.5  0.0 ");
  lVY.load(10, " 0 0 1 0  0.0  0.5  0.5  0.0  0.0  0.5 ");
  lVZ.load(10, " 0 0 0 1  0.0  0.0  0.0  0.5  0.5  0.5 ");

  assert(4 == Nfaces);

  IMat lEToV(8,4, "lEToV"), im84(8,4, "im84"), oFnodes(4,6, "oFnodes");

  set84(lEToV, 8,4, 
           a, e, g, h,
	         e, b, f, i,
	         g, f, c, j,
	         h, i, j, d,
	         e, g, h, i,
	         h, i, g, j,
	         e, f, g, i,
	         g, i, f, j);

  set46(oFnodes, 4,6, 
           a, e, b, f, c, g,
	         a, e, b, i, d, h,
	         b, f, c, j, d, i,
	         a, g, c, j, d, h);

  IMat vnum(gRowData, 4,3, "1 2 3  1 2 4  2 3 4  3 1 4");

  int lK = lEToV.num_rows();
  IMat lBCType(lK, Nfaces), tm1, tm2;
  IVec tv(3),tv1,tv2, oFn,vnp,ksids;
  int kk=0,ff=0,oo=0;
  for (kk=1; kk<=lK; ++kk) {
    for (ff=1; ff<=Nfaces; ++ff) {
      for (oo=1; oo<=Nfaces; ++oo) 
      {
        oFn = oFnodes.get_row(oo);
        vnp = vnum.get_row(ff);
        tm1 = lEToV(kk, vnp);  const IVec& knodes = dynamic_cast<const IVec&>(tm1);

      //tv = intersect(lEToV(k, vnum(p,All)), oFnodes(o,All));
        tv = intersect(knodes, oFn);

        if ( tv.length()==3 ) {
	        lBCType(kk, ff) = oo;
        }
      }
    }
  }

  int NV = VX.length()+1;
  int sp_len = NV + NV*NV;

  // sparse buffers   nnz  vals,triplet
  CSd newVX(sp_len,1,  NV,    1,  1);
  CSd newVY(sp_len,1,  NV,    1,  1);
  CSd newVZ(sp_len,1,  NV,    1,  1);

  Index1D II(1, NV-1);
  newVX(II,1) = VX;
  newVY(II,1) = VY;
  newVZ(II,1) = VZ;

  IVec ids("ids");
  int oldK = K, f1=0;

  for (int k1=1; k1<=oldK; ++k1) {
    if (refineflag(k1)) 
    {
      a = EToV(k1,1); 
      b = EToV(k1,2); 
      c = EToV(k1,3); 
      d = EToV(k1,4);

      e = NV + std::max(a*NV+b, b*NV + a);
      f = NV + std::max(b*NV+c, c*NV + b);
      g = NV + std::max(a*NV+c, c*NV + a);
      h = NV + std::max(a*NV+d, d*NV + a);
      i = NV + std::max(b*NV+d, d*NV + b);
      j = NV + std::max(c*NV+d, d*NV + c);

    //ks = [k1, K+1:K+7];
      IVec ks(1, k1);  ks.append(Range(K+1,K+7));

      //--------------------------
      // EToV(ks,:) = [a e g h;
		  //               e b f i;
		  //               g f c j;
		  //               h i j d;
		  //               e g h i;
		  //               h i g j;
		  //               e f g i;
		  //               g i f j];
      //--------------------------

      set84(im84, 8,4, 
            a, e, g, h,
		        e, b, f, i,
		        g, f, c, j,
		        h, i, j, d,
		        e, g, h, i,
		        h, i, g, j,
		        e, f, g, i,
		        g, i, f, j);

    //EToV(ks,All) = im84;
      EToV.merge_rows(ks, im84);

      for (f1=1; f1<=Nfaces; ++f1) 
      {
        tv = lBCType(All,f1);
        ids = find(tv, '!', 0);
        ksids = ks(ids);
        tm1 = lBCType(ids,f1);
        tm2 = BCType(k1, (const IVec&)tm1);

        // expand BCType to accommodate new range
        int maxI=ksids.max_val(), maxR=BCType.num_rows();
        if (maxI>maxR) {BCType.realloc(maxI, BCType.num_cols());}

        BCType(ksids,f1) = trans(tm2);
      }

      K += 7;

      newVX.set1(e,1, 0.5*(VX(a)+VX(b))); 
      newVX.set1(f,1, 0.5*(VX(b)+VX(c)));
      newVX.set1(g,1, 0.5*(VX(c)+VX(a)));
      newVX.set1(h,1, 0.5*(VX(a)+VX(d)));
      newVX.set1(i,1, 0.5*(VX(b)+VX(d)));
      newVX.set1(j,1, 0.5*(VX(c)+VX(d)));

      newVY.set1(e,1, 0.5*(VY(a)+VY(b)));
      newVY.set1(f,1, 0.5*(VY(b)+VY(c)));
      newVY.set1(g,1, 0.5*(VY(c)+VY(a)));
      newVY.set1(h,1, 0.5*(VY(a)+VY(d)));
      newVY.set1(i,1, 0.5*(VY(b)+VY(d)));
      newVY.set1(j,1, 0.5*(VY(c)+VY(d)));

      newVZ.set1(e,1, 0.5*(VZ(a)+VZ(b)));
      newVZ.set1(f,1, 0.5*(VZ(b)+VZ(c)));
      newVZ.set1(g,1, 0.5*(VZ(c)+VZ(a)));
      newVZ.set1(h,1, 0.5*(VZ(a)+VZ(d)));
      newVZ.set1(i,1, 0.5*(VZ(b)+VZ(d)));
      newVZ.set1(j,1, 0.5*(VZ(c)+VZ(d)));
    }
  }

  //-------------------------------------
  // drop duplicates and sort
  //-------------------------------------
  newVX.compress(true);
  newVY.compress(true);
  newVZ.compress(true);

//ids = sort(unique(EToV(:)), 'ascend');
  ids = unique(EToV);


  int len=ids.max_val(); 
  IVec gnum(len);
  gnum(ids) = Range(1,ids.length());

  VX = full( newVX, ids );
  VY = full( newVY, ids );
  VZ = full( newVZ, ids );

  // EToV = gnum(EToV);
  EToV.set_map(EToV, gnum);

  int NV_old = NV-1;        // local counters
  this->Nv = VX.length();   // update member variable

  umLOG(1, "Hrefine3D [%d] : old Nv = %4d, new Nv = %4d\n", ++refine_count, NV_old, Nv);
  umLOG(1, "                old K  = %4d, new K  = %4d\n\n", oldK, K);


#if (0)
  tetramesh(EToV, [VX', VY', VZ'])
#endif

}
コード例 #5
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the EC Factory so we can customize the EC
    TAO_EC_Default_Factory::init_svcs ();

    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    const ACE_TCHAR* ecname = ACE_TEXT ("EventService");
    const ACE_TCHAR* address = ACE_TEXT ("localhost");
    const ACE_TCHAR* iorfile = 0;
    u_short port = 12345;
    u_short listenport = 12345;
    int mcast = 1;

    for (int i = 0; argv[i] != 0; i++) {
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-ecname")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          ecname = argv[i];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-address")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          address = argv[i];
        } else {
          std::cerr << "Missing address" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-port")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          port = ACE_OS::atoi(argv[i]);
        } else {
          std::cerr << "Missing port" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-listenport")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          listenport = ACE_OS::atoi(argv[i]);
        } else {
          std::cerr << "Missing port" << std::endl;
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-iorfile")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          iorfile = argv[i];
        }
      } else if (ACE_OS::strcmp(argv[i], ACE_TEXT("-udp")) == 0) {
        mcast = 0;
      }
    }

    // Get the POA
    CORBA::Object_var object = orb->resolve_initial_references ("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow (object.in ());
    PortableServer::POAManager_var poa_manager = poa->the_POAManager ();
    poa_manager->activate ();

    // Create a local event channel and register it
    TAO_EC_Event_Channel_Attributes attributes (poa.in (), poa.in ());
    PortableServer::Servant_var<TAO_EC_Event_Channel> ec_impl =
      new TAO_EC_Event_Channel(attributes);
    ec_impl->activate ();
    PortableServer::ObjectId_var oid = poa->activate_object(ec_impl.in());
    CORBA::Object_var ec_obj = poa->id_to_reference(oid.in());
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(ec_obj.in());

    // Find the Naming Service.
    CORBA::Object_var obj = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context = CosNaming::NamingContextExt::_narrow(obj.in());

    // Bind the Event Channel using Naming Services
    CosNaming::Name_var name = root_context->to_name (ACE_TEXT_ALWAYS_CHAR (ecname));
    root_context->rebind(name.in(), ec.in());

    // Get a proxy push consumer from the EventChannel.
    RtecEventChannelAdmin::SupplierAdmin_var admin = ec->for_suppliers();
    RtecEventChannelAdmin::ProxyPushConsumer_var consumer =
      admin->obtain_push_consumer();

    // Instantiate an EchoEventSupplier_i servant.
    PortableServer::Servant_var<EchoEventSupplier_i> servant =
      new EchoEventSupplier_i(orb.in());

    // Register it with the RootPOA.
    oid = poa->activate_object(servant.in());
    CORBA::Object_var supplier_obj = poa->id_to_reference(oid.in());
    RtecEventComm::PushSupplier_var supplier =
      RtecEventComm::PushSupplier::_narrow(supplier_obj.in());

    // Connect to the EC.
    ACE_SupplierQOS_Factory qos;
    qos.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    consumer->connect_push_supplier (supplier.in (), qos.get_SupplierQOS ());

    // Initialize the address server with the desired address.
    // This will be used by the sender object and the multicast
    // receiver.
    ACE_INET_Addr send_addr (port, address);
    PortableServer::Servant_var<SimpleAddressServer> addr_srv_impl =
      new SimpleAddressServer(send_addr);

    PortableServer::ObjectId_var addr_srv_oid =
      poa->activate_object(addr_srv_impl.in());
    CORBA::Object_var addr_srv_obj = poa->id_to_reference(addr_srv_oid.in());
    RtecUDPAdmin::AddrServer_var addr_srv =
      RtecUDPAdmin::AddrServer::_narrow(addr_srv_obj.in());

    // Create and initialize the sender object
    PortableServer::Servant_var<TAO_ECG_UDP_Sender> sender =
                                TAO_ECG_UDP_Sender::create();
    TAO_ECG_UDP_Out_Endpoint endpoint;
    if (endpoint.dgram ().open (ACE_Addr::sap_any) == -1) {
      std::cerr << "Cannot open send endpoint" << std::endl;
      return 1;
    }

    // TAO_ECG_UDP_Sender::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the sender will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    sender->init (ec.in (), addr_srv.in (), clone);

    // Setup the subscription and connect to the EC
    ACE_ConsumerQOS_Factory cons_qos_fact;
    cons_qos_fact.start_disjunction_group ();
    cons_qos_fact.insert (ACE_ES_EVENT_SOURCE_ANY, ACE_ES_EVENT_ANY, 0);
    RtecEventChannelAdmin::ConsumerQOS sub = cons_qos_fact.get_ConsumerQOS ();
    sender->connect (sub);

    // Create and initialize the receiver
    PortableServer::Servant_var<TAO_ECG_UDP_Receiver> receiver =
                                      TAO_ECG_UDP_Receiver::create();

    // TAO_ECG_UDP_Receiver::init() takes a TAO_ECG_Refcounted_Endpoint.
    // If we don't clone our endpoint and pass &endpoint, the receiver will
    // attempt to delete endpoint during shutdown.
    TAO_ECG_Refcounted_Endpoint clone2 (new TAO_ECG_UDP_Out_Endpoint (endpoint));
    receiver->init (ec.in (), clone2, addr_srv.in ());

    // Setup the registration and connect to the event channel
    ACE_SupplierQOS_Factory supp_qos_fact;
    supp_qos_fact.insert (MY_SOURCE_ID, MY_EVENT_TYPE, 0, 1);
    RtecEventChannelAdmin::SupplierQOS pub = supp_qos_fact.get_SupplierQOS ();
    receiver->connect (pub);

    // Create the appropriate event handler and register it with the reactor
    auto_ptr<ACE_Event_Handler> eh;
    if (mcast) {
      auto_ptr<TAO_ECG_Mcast_EH> mcast_eh(new TAO_ECG_Mcast_EH (receiver.in()));
      mcast_eh->reactor (orb->orb_core ()->reactor ());
      mcast_eh->open (ec.in());
      ACE_auto_ptr_reset(eh,mcast_eh.release());
      //eh.reset(mcast_eh.release());
    } else {
      auto_ptr<TAO_ECG_UDP_EH> udp_eh (new TAO_ECG_UDP_EH (receiver.in()));
      udp_eh->reactor (orb->orb_core ()->reactor ());
      ACE_INET_Addr local_addr (listenport);
      if (udp_eh->open (local_addr) == -1) {
        std::cerr << "Cannot open EH" << std::endl;
      }
      ACE_auto_ptr_reset(eh,udp_eh.release());
      //eh.reset(udp_eh.release());
    }

    // Create an event (just a string in this case).
    const CORBA::String_var eventData = CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (ecname));

    // Create an event set for one event
    RtecEventComm::EventSet event (1);
    event.length (1);

    // Initialize event header.
    event[0].header.source = MY_SOURCE_ID;
    event[0].header.ttl = 1;
    event[0].header.type = MY_EVENT_TYPE;

    // Initialize data fields in event.
    event[0].data.any_value <<= eventData;

    if (iorfile != 0) {
      CORBA::String_var str = orb->object_to_string( ec.in() );
      std::ofstream iorFile( ACE_TEXT_ALWAYS_CHAR(iorfile) );
      iorFile << str.in() << std::endl;
      iorFile.close();
    }
    std::cout << "Starting main loop" << std::endl;

    const int EVENT_DELAY_MS = 10;

    while (1) {
      consumer->push (event);

      ACE_Time_Value tv(0, 1000 * EVENT_DELAY_MS);
      orb->run(tv);
    }

    orb->destroy();
    return 0;
  }
  catch(const CORBA::Exception& exc)
  {
    std::cerr << "Caught CORBA::Exception" << std::endl << exc << std::endl;
  }
  return 1;
}
コード例 #6
0
ファイル: mod_sd.cpp プロジェクト: colemonnahan/admb
void function_minimizer::sd_routine(void)
{
  int nvar=initial_params::nvarcalc(); // get the number of active parameters
  dvector x(1,nvar);
  initial_params::xinit(x); // get the number of active parameters

  initial_params::restore_start_phase();
  int nvar1=initial_params::nvarcalc(); // get the number of active parameters
  int num_sdrep_types=stddev_params::num_stddev_params +
    initial_params::num_active_calc();

  param_labels.allocate(1,num_sdrep_types);
  param_size.allocate(1,num_sdrep_types);

  int ii=1;
  size_t max_name_length = 0;
  for (int i=0;i<initial_params::num_initial_params;i++)
  {
    //if ((initial_params::varsptr[i])->phase_start
     // <= initial_params::current_phase)
    if (withinbound(0,(initial_params::varsptr[i])->phase_start,
      initial_params::current_phase))
    {
      param_labels[ii]=
       (initial_params::varsptr[i])->label();
      param_size[ii]=
       (initial_params::varsptr[i])->size_count();
      if (max_name_length<param_labels[ii].size())
      {
        max_name_length=param_labels[ii].size();
      }
      ii++;
    }
  }

  int start_stdlabels=ii;
  for (int i=0;i< stddev_params::num_stddev_params;i++)
  {
    param_labels[ii]=
      stddev_params::stddevptr[i]->label();
    param_size[ii]=
      stddev_params::stddevptr[i]->size_count();
    if (max_name_length<param_labels[ii].size())
    {
      max_name_length=param_labels[ii].size();
    }
    ii++;
  }
  int end_stdlabels=ii-1;

  int ndvar=stddev_params::num_stddev_calc();
  dvector scale(1,nvar1);   // need to get scale from somewhere
  dvector v(1,nvar);  // need to read in v from model.rep
  dmatrix S(1,nvar,1,nvar);
  {
    uistream cif("admodel.cov");
    int tmp_nvar = 0;
    cif >> tmp_nvar;
    if (nvar !=tmp_nvar)
    {
      cerr << "Incorrect number of independent variables in file"
        " model.cov" << endl;
      exit(1);
    }
    cif >> S;
    if (!cif)
    {
      cerr << "error reading covariance matrix from model.cov" << endl;
      exit(1);
    }
  }
  int sgn;
  initial_params::stddev_scale(scale,x);
  double lndet=-ln_det(S,sgn)-2.0*sum(log(scale));
  initial_params::set_active_random_effects();
  //int nvar1=initial_params::nvarcalc();
  dvector diag(1,nvar1+ndvar);
  dvector tmp(1,nvar1+ndvar);

  {
    ofstream ofs("admodel.tmp");

    #if defined(__GNU__) || defined(DOS386)  || defined(__GNUDOS__)
    // *******************************************************
    // *******************************************************
    {
      if (nvar==nvar1)  // no random effects
      {
        for (int i=1;i<=nvar;i++)
        {
          for (int j=1;j<=i;j++)
          {
            tmp(j)=S(i,j)*scale(i)*scale(j);
            ofs << tmp(j) << " ";
          }
          ofs << endl;
          diag(i)=tmp(i);
        }
        dmatrix tv(1,ndvar,1,nvar1);
        adstring tmpstring="admodel.dep";
        if (ad_comm::wd_flag)
           tmpstring = ad_comm::adprogram_name + ".dep";
        cifstream cif((char*)tmpstring);

        int tmp_nvar = 0, tmp_ndvar = 0;
        cif >> tmp_nvar >> tmp_ndvar;
        if (tmp_nvar!=nvar1)
        {
          cerr << " tmp_nvar != nvar1 in file " << tmpstring
                 << endl;
          ad_exit(1);
        }
        if (ndvar>0)
        {
          cif >> tv;
          dvector tmpsub(1,nvar);
          for (int i=1;i<=ndvar;i++)
          {
            for (int j=1;j<=nvar;j++)
            {
              tmpsub(j)=(tv(i)*S(j))*scale(j);
            }
            ofs << tmpsub << "  ";
            tmpsub=tv(i)*S;
            for (int j=1;j<=i;j++)
            {
              tmp(nvar+j)=tmpsub*tv(j);
              ofs << tmp(nvar+j) << " ";
            }
            diag(i+nvar)=tmp(i+nvar);

            if (diag(i+nvar)<=0.0)
            {
              cerr << "Estimated covariance matrix may not"
               " be positive definite" << endl;
              cerr << sort(eigenvalues(S)) << endl;
            }
            ofs << endl;
          }
        }
      }
      else  // have random effects
      {
        dmatrix tv(1,ndvar,1,nvar1);
        adstring tmpstring="admodel.dep";
        if (ad_comm::wd_flag)
           tmpstring = ad_comm::adprogram_name + ".dep";
        cifstream cif((char*)tmpstring);

        int tmp_nvar = 0, tmp_ndvar = 0;
        cif >> tmp_nvar >> tmp_ndvar;
        if (tmp_nvar!=nvar1)
        {
          cerr << " tmp_nvar != nvar1 in file " << tmpstring
                 << endl;
          ad_exit(1);
        }

        dmatrix BS(1,nvar1,1,nvar1);
        BS.initialize();
        get_bigS(ndvar,nvar1,nvar,S,BS,scale);

        {
          tmpstring = ad_comm::adprogram_name + ".bgs";
          uostream uos((char*)(tmpstring));
          if (!uos)
          {
            cerr << "error opening file " << tmpstring << endl;
            ad_exit(1);
          }
          uos << nvar1;
          uos << BS;
          if (!uos)
          {
            cerr << "error writing to file " << tmpstring << endl;
            ad_exit(1);
          }
        }

        for (int i=1;i<=nvar1;i++)
        {
          for (int j=1;j<=i;j++)
          {
            tmp(j)=BS(i,j)*scale(i)*scale(j);
            ofs << tmp(j) << " ";
          }
          ofs << endl;
          diag(i)=tmp(i);
        }

        if (ndvar>0)
        {
          cif >> tv;
          dvector tmpsub(1,nvar1);
          for (int i=1;i<=ndvar;i++)
          {
            for (int j=1;j<=nvar1;j++)
            {
              tmpsub(j)=(tv(i)*BS(j))*scale(j);
            }
            ofs << tmpsub << "  ";
            tmpsub=tv(i)*BS;
            for (int j=1;j<=i;j++)
            {
              tmp(nvar1+j)=tmpsub*tv(j);
              ofs << tmp(nvar1+j) << " ";
            }
            diag(i+nvar1)=tmp(i+nvar1);

            if (diag(i+nvar1)<=0.0)
            {
              if (norm(tv(i))>1.e-100)
              {
                cerr << "Estimated covariance matrix may not"
                 " be positive definite" << endl;
                cerr << sort(eigenvalues(BS)) << endl;
              }
            }
            ofs << endl;
          }
        }
      }
コード例 #7
0
ファイル: sender.cpp プロジェクト: OspreyHub/ATCD
int
ACE_TMAIN (int argc,
      ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      CORBA::Object_var obj
        = orb->resolve_initial_references ("RootPOA");

      // Get the POA_var object from Object_var
      PortableServer::POA_var root_poa
        = PortableServer::POA::_narrow (obj.in ());

      PortableServer::POAManager_var mgr
        = root_poa->the_POAManager ();

      mgr->activate ();

      // Initialize the AV Stream components.
/*      TAO_AV_CORE::instance ()->init (orb.in (),
                                      root_poa.in ()); */

      // Initialize the AVStreams components.
      TAO_AV_CORE::instance ()->init (orb.in (), root_poa.in ());

      // Initialize the Sender.
      int result = 0;
      result = SENDER::instance ()->init (argc,
                                          argv);

      if (result < 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Sender::init failed\n"),
                          -1);

      // Make sure we have a valid <output_file>
      output_file = ACE_OS::fopen (output_file_name,
                                   "w");
      if (output_file == 0)
        ACE_ERROR_RETURN ((LM_DEBUG,
                           "Cannot open output file %s\n",
                           output_file_name),
                          -1);

      else
        ACE_DEBUG ((LM_DEBUG,
                    "File Opened Successfully\n"));

      // Start sending data.
      result = SENDER::instance ()->pace_data ();
      ACE_Time_Value tv(3,0);
      orb->run (tv);
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Sender Failed\n");
      return -1;
    }

  SENDER::close ();  // Explicitly finalize the Unmanaged_Singleton.

  return 0;
}
コード例 #8
0
int main(int argc, char* argv[]) 
{

    if (argc<2)
    {
      ACE_OS::printf ("usage: %s <object_name>\n", argv[0]);
      return -1;
    }
    
    
    try
	{
	ACE_CString g_strCmdLn;
	for (int i=argc-1; i>=0; i--)
	    g_strCmdLn = ACE_CString(argv[i])+ " " + g_strCmdLn;

	if (g_strCmdLn.find("-ORBDottedDecimalAddresses")==ACE_CString::npos)
	    g_strCmdLn += " -ORBDottedDecimalAddresses 1";

	ACE_TCHAR **m_argv = argv;
	int m_argc = argc;
	ACE_OS::string_to_argv((ACE_TCHAR*)g_strCmdLn.c_str(),
			 m_argc,
			 m_argv);
	BACI_CORBA::InitCORBA(m_argc, m_argv);

	LoggingProxy EP_log (0, 0, 31, 0);
	LoggingProxy::init (&EP_log);

	/**
	 * Get reference to a device
	 */

	char fileName[64];
	sprintf(fileName, "file://%s.ior", argv[1]);
	CORBA::Object_var object = BACI_CORBA::getORB()->string_to_object (fileName);
	

	if (CORBA::is_nil(object.in())) 
	    {
	    ACE_DEBUG ((LM_DEBUG, "Cannot get Object"));
	    return -1;
	    }

	// Try to narrow the object reference to a PowerSupply reference.
	ENUMPROP_TEST::enumpropTestDevice_var dev = ENUMPROP_TEST::enumpropTestDevice::_narrow (object.in ());
	
	if (CORBA::is_nil(dev.in())) 
	    {
	    ACS_SHORT_LOG((LM_DEBUG, "Failed to narrow enumnTestDevice "));
	    return 0;
	    }
	ACS_SHORT_LOG((LM_DEBUG, "Device narrowed."));

	// Get current stat
	ENUMPROP_TEST::ROStates_var currentState = dev->currentState();
	

	//   get states description	
	ACS::stringSeq_var description = currentState->statesDescription( );
	

	AlarmCBpattern alarmCB (currentState.in());
        ACS::Alarmpattern_var alarmCBObj = alarmCB._this();

        ACS::CBDescIn desc;
	desc.id_tag = 1;

	ACS::Subscription_var monitor = currentState->new_subscription_AlarmEnum(alarmCBObj.in(), desc);
	//	monitor->set_timer_trigger(10000000);

	ACS_SHORT_LOG((LM_DEBUG, "(main thread) Going in main loop sleep..."));
	ACE_Time_Value tv(5);
	BACI_CORBA::getORB()->run(tv);

	ACS_SHORT_LOG((LM_DEBUG, "(main thread) Exit ... "));
	monitor->destroy();

        /* Allow time for the done() callback to come back */
	BACI_CORBA::getORB()->run(tv);

	BACI_CORBA::DoneCORBA();
	}
    catch( CORBA::Exception &ex )
	{
	ACE_PRINT_EXCEPTION (ex,"Error!");
	return -1;
	}
    ACE_CHECK_RETURN (-1);


    return 0;
}
コード例 #9
0
ファイル: cg_events.c プロジェクト: hettoo/racesow
/*
* CG_Event_Fall
*/
void CG_Event_Fall( entity_state_t *state, int parm )
{
	if( ISVIEWERENTITY( state->number ) )
	{
		if( cg.frame.playerState.pmove.pm_type != PM_NORMAL )
		{
			CG_SexedSound( state->number, CHAN_AUTO, "*fall_0", cg_volume_players->value );
			return;
		}

		CG_ViewWeapon_StartFallKickEff( parm );

		if( parm > 0 )
			CG_DamageIndicatorAdd( parm, tv( 0, 0, 1 ) );
	}

	if( parm > 10 )
	{
		CG_SexedSound( state->number, CHAN_PAIN, "*fall_2", cg_volume_players->value );
		switch( (int)brandom( 0, 3 ) )
		{
		case 0:
			CG_PModel_AddAnimation( state->number, 0, TORSO_PAIN1, 0, EVENT_CHANNEL );
			break;
		case 1:
			CG_PModel_AddAnimation( state->number, 0, TORSO_PAIN2, 0, EVENT_CHANNEL );
			break;
		case 2:
		default:
			CG_PModel_AddAnimation( state->number, 0, TORSO_PAIN3, 0, EVENT_CHANNEL );
			break;
		}
	}
	else if( parm > 0 )
	{
		CG_SexedSound( state->number, CHAN_PAIN, "*fall_1", cg_volume_players->value );
	}
	else
		CG_SexedSound( state->number, CHAN_PAIN, "*fall_0", cg_volume_players->value );

	// smoke effect
	if( parm > 0 && ( cg_cartoonEffects->integer & 2 ) )
	{
		vec3_t start, end;
		trace_t trace;

		if( ISVIEWERENTITY( state->number ) )
			VectorCopy( cg.predictedPlayerState.pmove.origin, start );
		else
			VectorCopy( state->origin, start );

		VectorCopy( start, end );
		end[2] += playerbox_stand_mins[2] - 48.0f;

		CG_Trace( &trace, start, vec3_origin, vec3_origin, end, state->number, MASK_PLAYERSOLID );
		if( trace.ent == -1 )
		{
			start[2] += playerbox_stand_mins[2] + 8;
			CG_DustCircle( start, tv( 0, 0, 1 ), 50, 12 );
		}
		else if( !(trace.surfFlags & SURF_NODAMAGE) )
		{
			VectorMA( trace.endpos, 8, trace.plane.normal, end );
			CG_DustCircle( end, trace.plane.normal, 50, 12 );
		}
	}
}
コード例 #10
0
void EnMenu::updateEntity( float deltaTime )
{
    // main control state machine
    switch ( _menuState )
    {
        case None:
            break;

        case BeginIntro:
        {
            // let the mouse disappear for intro
            gameutils::GuiUtils::get()->showMousePointer( false );
            _menuState = Intro;
        }
        break;

        case Intro:
        {
            _intro->update( deltaTime );
        }
        break;

        // in order to show up the loading pic we have to activate it
        //  and do the actual level loading one step later, as loading a level blocks the main loop :-(
        case BeginLoadingLevel:
        {
            _p_loadingWindow->show();
            // show up the loading window
            gameutils::GuiUtils::get()->showMousePointer( false ); // let the mouse disappear
            _menuState = PrepareLoadingLevel;
        }
        break;

        case PrepareLoadingLevel:
        {
            // unload level, don't keep physics and entities
            // note: the menu entity is persistent anyway, it handles the level switch itself!
            yaf3d::LevelManager::get()->unloadLevel( true, true );
            _menuState  = LoadingLevel;

            // set the proper game state
            yaf3d::GameState::get()->setState( yaf3d::GameState::StartingLevel );
        }
        break;

        case LoadingLevel:
        {
            // problems getting level file info?
            if ( !_queuedLevelFile.length() )
            {
                _levelSelectDialog->enable( false );
                _menuState = Visible;
                break;
            }

            yaf3d::LevelManager::get()->loadLevel( _queuedLevelFile );
            _queuedLevelFile = ""; // reset the queue

            // now load the player and its other entities
            std::string playerCfgFile;
            vrc::gameutils::PlayerUtils::get()->getPlayerConfig( yaf3d::GameState::get()->getMode(), false, playerCfgFile );
            yaf3d::LevelManager::get()->loadEntities( playerCfgFile );

            // complete level loading
            yaf3d::LevelManager::get()->finalizeLoading();

            // set flag that we have loaded a level; some menu oprions depend on this flag
            _levelLoaded = true;

            // store level scene's static mesh for later switching
            _levelScene = yaf3d::LevelManager::get()->getStaticMesh();

            // now start client networking when we joined to a session
            if ( yaf3d::GameState::get()->getMode() == yaf3d::GameState::Client )
            {
                // try to start client
                try
                {
                    yaf3d::NetworkDevice::get()->startClient();

                    // send the notification on established network session
                    yaf3d::EntityNotification ennotify( YAF3D_NOTIFY_NETWORKING_ESTABLISHED );
                    yaf3d::EntityManager::get()->sendNotification( ennotify );
                }
                catch ( const yaf3d::NetworkException& e )
                {

                    yaf3d::MessageBoxDialog* p_msg = new yaf3d::MessageBoxDialog( "Attention", e.what(), yaf3d::MessageBoxDialog::OK, true );
                    p_msg->show();

                    _menuState = PrepareUnloadLevel;

                    // play attention sound
                    vrc::gameutils::GuiUtils::get()->playSound( GUI_SND_NAME_ATTENTION );

                    return;
                }
            }

            // leave the menu system
            leave();

            // now fade out the loading window
            _menuState = FadeIntoLevel;

            // set the proper game state
            yaf3d::GameState::get()->setState( yaf3d::GameState::MainLoop );
        }
        break;

        case FadeIntoLevel:
        {
            _fadeIntoLevelTimer += deltaTime;
            float alpha = 1.0f - ( _fadeIntoLevelTimer / FADE_INTOLEVEL_TIME );
            _p_loadingWindow->setAlpha( alpha );

            if ( _fadeIntoLevelTimer > FADE_INTOLEVEL_TIME )
            {
                _fadeIntoLevelTimer = 0.0f;

                // restore the alpha and hide the loading window now
                _p_loadingWindow->removeChildWindow( _p_loadingOverly );
                _p_loadingWindow->setAlpha( 1.0f );
                _p_loadingWindow->hide();

                // disable level select dialog now freeing up the resources ( textures )
                _levelSelectDialog->enable( false );
                _p_menuWindow->disable();

                // change to state hidden
                _menuState = Hidden;

                // free up the client level file object which was previously used for getting the loading pic
                if ( _p_clientLevelFiles )
                    delete _p_clientLevelFiles;
                _p_clientLevelFiles = NULL;

            }
        }
        break;

        // unloading a level must be delayed one step due to freeing up graphics objects
        case PrepareUnloadLevel:
        {
            _menuState = UnloadLevel;
            // set the proper game state
            yaf3d::GameState::get()->setState( yaf3d::GameState::LeavingLevel );
            yaf3d::LevelManager::get()->unloadLevel();
        }
        break;

        case UnloadLevel:
        {
            // release the level scene node
            if ( _levelScene.valid() )
                _levelScene = NULL;

            switchMenuScene( true );

            // set the proper game state
            yaf3d::GameState::get()->setState( yaf3d::GameState::MainLoop );

            // reset the game mode
            yaf3d::GameState::get()->setMode( yaf3d::GameState::UnknownMode );

            _menuState = Visible;
        }
        break;

        // currently we do nothing in hidden state, just idle
        case Hidden:
            break;

        case Visible:
        {
            _settingsDialog->update( deltaTime );

            if ( _menuAnimationPath.get() )
            {
                // play the camera animation during the user is in menu
                vrc::gameutils::TransformationVisitor tv( osg::NodeVisitor::TRAVERSE_ALL_CHILDREN ); // see vrc_utils.h in framework
                _menuAnimationPath->accept( tv );
                const osg::Matrixf&  mat = tv.getMatrix();
                osg::Quat rot;
                mat.get( rot );
                osg::Vec3f pos = mat.getTrans();
                _p_cameraControl->setCameraTransformation( pos, rot );
            }

            // handle menu idling
            {
                if ( _idleCounter >= 0.0 )
                {
                    _idleCounter -= deltaTime;
                }

                if ( _idleCounter < 0.0 )
                {
                    // start idle mode
                    _p_menuWindow->hide();
                    yaf3d::GuiManager::get()->showMousePointer( false );
                }
            }
        }
        break;

        case Quitting:
        {
            // quit the application now
            yaf3d::Application::get()->stop();
        }
        break;

        default:
            assert( NULL && "invalid menu state!" );

    }

    // control the menu background sound on entering and leaving menu
    switch ( _menuSoundState )
    {
        case SoundStopped:
            break;

        case SoundFadeIn:
        {
            _p_backgrdSound->startPlaying( true );
            _menuSoundState = SoundFadingIn;
        }
        break;

        case SoundFadingIn:
        {
            _soundFadingCnt += deltaTime;
            if ( _soundFadingCnt > BCKRGD_SND_FADEIN_PERIOD )
            {
                _soundFadingCnt = 0.0f;
                _menuSoundState = SoundStopped;
                break;
            }

            float volume = std::min( _soundFadingCnt / BCKRGD_SND_FADEIN_PERIOD, _backgrdSoundVolume );
            _p_backgrdSound->setVolume( volume );
        }
        break;

        case SoundFadeOut:
        {
            _soundFadingCnt += deltaTime;
            if ( _soundFadingCnt > BCKRGD_SND_FADEIN_PERIOD )
            {
                _p_backgrdSound->stopPlaying( true );
                _soundFadingCnt = 0.0f;
                _menuSoundState = SoundStopped;
                break;
            }

            float volume = std::max( _backgrdSoundVolume * ( 1.0f - _soundFadingCnt / BCKRGD_SND_FADEOUT_PERIOD ), 0.0f );
            _p_backgrdSound->setVolume( volume );
        }
        break;

        default:
            assert( NULL && "unknown menu sound state!" );
    }
}
コード例 #11
0
ファイル: ai_movement.c プロジェクト: Racenet/racesow
//==========================================
// AI_SpecialMove
// Handle special cases of crouch/jump
// If the move is resolved here, this function returns qtrue.
//==========================================
qboolean AI_SpecialMove( edict_t *self, usercmd_t *ucmd )
{
	vec3_t forward;
	trace_t tr;
	vec3_t boxmins, boxmaxs, boxorigin;

	// Get current direction
	AngleVectors( tv( 0, self->s.angles[YAW], 0 ), forward, NULL, NULL );

	// make sure we are blocked
	VectorCopy( self->s.origin, boxorigin );
	VectorMA( boxorigin, 8, forward, boxorigin ); //move box by 8 to front
	G_Trace( &tr, self->s.origin, self->r.mins, self->r.maxs, boxorigin, self, MASK_AISOLID );
	if( !tr.startsolid && tr.fraction == 1.0 )  // not blocked
		return qfalse;

	//ramps
	if( ISWALKABLEPLANE( &tr.plane ) )
		return qfalse;

	if( self->ai.status.moveTypesMask & LINK_CROUCH || self->is_swim )
	{
		// crouch box
		VectorCopy( self->s.origin, boxorigin );
		VectorCopy( self->r.mins, boxmins );
		VectorCopy( self->r.maxs, boxmaxs );
		boxmaxs[2] = 14; // crouched size
		VectorMA( boxorigin, 8, forward, boxorigin ); // move box by 8 to front
		// see if blocked
		G_Trace( &tr, boxorigin, boxmins, boxmaxs, boxorigin, self, MASK_AISOLID );
		if( !tr.startsolid ) // can move by crouching
		{
			ucmd->forwardmove = 1;
			ucmd->upmove = -1;
			return qtrue;
		}
	}

	if( self->ai.status.moveTypesMask & LINK_JUMP && self->groundentity )
	{
		// jump box
		VectorCopy( self->s.origin, boxorigin );
		VectorCopy( self->r.mins, boxmins );
		VectorCopy( self->r.maxs, boxmaxs );
		VectorMA( boxorigin, 8, forward, boxorigin ); // move box by 8 to front
		//
		boxorigin[2] += ( boxmins[2] + AI_JUMPABLE_HEIGHT ); // put at bottom + jumpable height
		boxmaxs[2] = boxmaxs[2] - boxmins[2]; // total player box height in boxmaxs
		boxmins[2] = 0;

		G_Trace( &tr, boxorigin, boxmins, boxmaxs, boxorigin, self, MASK_AISOLID );
		if( !tr.startsolid ) // can move by jumping
		{
			ucmd->forwardmove = 1;
			ucmd->upmove = 1;

			return qtrue;
		}
	}

	// nothing worked, check for turning
	return AI_CheckEyes( self, ucmd );
}
コード例 #12
0
ファイル: mom_mach.c プロジェクト: altair4/pbspro
/**
 * @brief
 *      Internal session cpu time decoding routine.
 *
 * @param[in] job - a job pointer.
 *
 * @return      ulong
 * @retval      sum of all cpu time consumed for all tasks executed by the job, in seconds,
 *              adjusted by cputfactor.
 *
 */
static unsigned long
cput_sum(job *pjob)
{
	ulong			 cputime, addtime;
	int			 i;
	int			 nps = 0;
	int			taskprocs;
	psinfo_t		*pi;
	task			*ptask;
	ulong			tcput;

	cputime = 0;
	for (ptask = (task *)GET_NEXT(pjob->ji_tasks);
		ptask != NULL;
		ptask = (task *)GET_NEXT(ptask->ti_jobtask)) {

		/* DEAD task */
		if (ptask->ti_qs.ti_sid <= 1) {
			cputime += ptask->ti_cput;
			continue;
		}

		tcput = 0;
		taskprocs = 0;
		for (i=0; i<nproc; i++) {
			pi = &proc_info[i];

			/* is this process part of the task? */
			if (ptask->ti_qs.ti_sid != pi->pr_sid)
				continue;

			nps++;
			taskprocs++;
			if (pi->pr_nlwp == 0) {		/* zombie */
				if ((pi->pr_sid != pi->pr_pid) &&
					(pi->pr_ppid != mom_pid))
					continue;

				/* top of session/job, record it */
				tcput += tv(pi->pr_time);
				DBPRT(("%s: task %08.8X ses %d pid %d "
					"(zombie) cputime %lu\n", __func__,
					ptask->ti_qs.ti_task,
					pi->pr_sid, pi->pr_pid, tcput))
			} else {
				addtime = tv(pi->pr_time) + tv(pi->pr_ctime);

				tcput += addtime;
				DBPRT(("%s: task %08.8X ses %d pid %d "
					"cputime %lu\n", __func__,
					ptask->ti_qs.ti_task, pi->pr_sid,
					pi->pr_pid, tcput))
			}
		}
		if (tcput > ptask->ti_cput)
			ptask->ti_cput = tcput;
		cputime += ptask->ti_cput;
		DBPRT(("%s: task %08.8X cput %lu total %lu\n", __func__,
			ptask->ti_qs.ti_task, ptask->ti_cput, cputime))

		if (taskprocs == 0) {
			sprintf(log_buffer,
				"no active process for task %8.8X",
				ptask->ti_qs.ti_task);
			log_event(PBSEVENT_JOB, PBS_EVENTCLASS_JOB,
				LOG_INFO, pjob->ji_qs.ji_jobid,
				log_buffer);
			ptask->ti_qs.ti_status = TI_STATE_EXITED;
			task_save(ptask);
			exiting_tasks = 1;
		}
	}
コード例 #13
0
ファイル: g_teamplay.c プロジェクト: MonkeyHarris/monkey-mod
void cashspawn_think( edict_t *self )
{
	edict_t	*cash;

	if ((num_cash_items > MAX_CASH_ITEMS) || (level.modeset == MATCHSETUP) || (level.modeset == MATCHCOUNT) || (level.modeset == PREGAME))
	{
		self->nextthink = level.time + self->delay;
		return;
	}

	// spawn some money
	cash = G_Spawn();

	VectorCopy( self->s.origin, cash->s.origin );
	cash->movetype = MOVETYPE_BOUNCE;
	cash->solid = SOLID_TRIGGER;

	AngleVectors( self->s.angles, cash->velocity, NULL, NULL );
	VectorScale( cash->velocity, self->speed, cash->velocity );

	// randomize the velocity a bit
	VectorAdd( cash->velocity, tv( crandom()*self->speed*0.3, crandom()*self->speed*0.3, crandom()*self->speed*0.15 ), cash->velocity );

	cash->s.renderfx2 |= RF2_NOSHADOW;

	// FIXME: doh this doesn't work, need to spawn actual item's, so the HUD is updated automatically when picking up

	if (!strcmp(self->type, "cashroll"))
	{	// small dollar notes
		cash->s.modelindex = gi.modelindex( "models/pu_icon/cash/tris.md2" );
		cash->gravity = 0.1 + random()*0.5;

		cash->think = cashroll_animate;
		cash->nextthink = level.time + 0.1;
		cash->s.angles[PITCH] = 10;
		VectorSet( cash->avelocity, 0, 10000 * cash->gravity, 0 );

		VectorSet( cash->mins, -4, -4, -15 );
		VectorSet( cash->maxs,  4,  4, -13 );

		cash->item = FindItem("Cash");

		cash->currentcash = CASH_ROLL;
		cash->touch = cash_touch;

		cash->timestamp = level.time + 60;

		cash->think = cashroll_animate;
		cash->nextthink = level.time + 0.1;
	}
	else
	{
		cash->s.modelindex = gi.modelindex( "models/pu_icon/money/money_sm.md2" );
		cash->gravity = 1.0;

		VectorSet( cash->mins, -12, -12, -15 );
		VectorSet( cash->maxs,  12,  12,  10 );

		cash->item = FindItem("Small Cash Bag");

		cash->currentcash = CASH_BAG;
		cash->touch = cash_touch;

		cash->think = cash_kill;
		cash->nextthink = level.time + 60;
	}

	num_cash_items++;

	self->nextthink = level.time + self->delay;

}
コード例 #14
0
ファイル: g_items.c プロジェクト: basecq/q2dos
/*
================
droptofloor
================
*/
void droptofloor (edict_t *ent)
{
	trace_t		tr;
	vec3_t		dest;
	float		*v;

	v = tv(-15,-15,-15);
	VectorCopy (v, ent->mins);
	v = tv(15,15,15);
	VectorCopy (v, ent->maxs);

	if (ent->model)
		gi.setmodel (ent, ent->model);
	else
		gi.setmodel (ent, ent->item->world_model);
	ent->solid = SOLID_TRIGGER;
	ent->movetype = MOVETYPE_TOSS;  
	ent->touch = Touch_Item;

	v = tv(0,0,-128);
	VectorAdd (ent->s.origin, v, dest);

	tr = gi.trace (ent->s.origin, ent->mins, ent->maxs, dest, ent, MASK_SOLID);
	if (tr.startsolid)
	{
		gi.dprintf(DEVELOPER_MSG_GAME, "droptofloor: %s startsolid at %s\n", ent->classname, vtos(ent->s.origin));
		G_FreeEdict (ent);
		return;
	}

	VectorCopy (tr.endpos, ent->s.origin);

	if (ent->team)
	{
		ent->flags &= ~FL_TEAMSLAVE;
		ent->chain = ent->teamchain;
		ent->teamchain = NULL;

		ent->svflags |= SVF_NOCLIENT;
		ent->solid = SOLID_NOT;
		if (ent == ent->teammaster)
		{
			ent->nextthink = level.time + FRAMETIME;
			ent->think = DoRespawn;
		}
	}

	if (ent->spawnflags & ITEM_NO_TOUCH)
	{
		ent->solid = SOLID_BBOX;
		ent->touch = NULL;
		ent->s.effects &= ~EF_ROTATE;
		ent->s.renderfx &= ~RF_GLOW;
	}

	if (ent->spawnflags & ITEM_TRIGGER_SPAWN)
	{
		ent->svflags |= SVF_NOCLIENT;
		ent->solid = SOLID_NOT;
		ent->use = Use_Item;
	}

	gi.linkentity (ent);
}
コード例 #15
0
ファイル: decarddevnode.cpp プロジェクト: nykma/ykt4sungard
int DC_Service_Request::do_request(KSG_WORK_SVR_HANDLER *handle)
{
	ACE_Message_Block *mblk = handle->mblk_;
	ACE_SOCK_Stream peer;
	ACE_Message_Block *resp_buf;
	unsigned char *msg_begin = (unsigned char*)mblk->rd_ptr();
	unsigned char *out_buf;
	unsigned char crc_code[4];
	int data_len = mblk->length();
	short pack_len;
	int len;
	int ret;
	peer.set_handle(handle->handle_);
	ACE_HEX_DUMP((LM_DEBUG,mblk->rd_ptr(),mblk->length()));

	if(msg_begin[0]!=0xC0 && msg_begin[data_len]!=0xC1)
	{
		ACE_DEBUG((LM_ERROR,"收到数据包起始符错误..."));
		return -1;
	}
	BUF_2_SHORT_BE(pack_len,(msg_begin+1));
	if(data_len - 3 < pack_len )
	{
		ACE_DEBUG((LM_ERROR,"收到错误数据包长度错误..."));
		return -1;
	}
	// check crc
	/*
	pack_len = GenerateCRC16(msg_begin+3,data_len-3-3);
	SHORT_2_BUF_BE(pack_len,crc_code);
	if(memcmp(crc_code,msg_begin+data_len-3,2)!=0)
	{
		ACE_DEBUG((LM_ERROR,"收到数据包CRC校验错误..."));
		return 0;
	}
	*/
	if(calc_sum(msg_begin+3,data_len-3-2)!=msg_begin[data_len-2])
	{
		ACE_DEBUG((LM_ERROR,"收到数据包CRC校验错误..."));
		return 0;
	}
	ACE_NEW_RETURN(resp_buf,ACE_Message_Block(128),-1);
	len = 0;
	out_buf = (unsigned char*)resp_buf->wr_ptr();
	out_buf[0]=0xC2;
	out_buf[3]=msg_begin[3];
	switch(msg_begin[3])
	{
	case 0x70:
		ret = do_upload_serial(msg_begin,data_len,out_buf+4,len);
		break;
	case 0x71:
		ret = do_download_blkcard(msg_begin,data_len,out_buf+4,len);
		break;
	default:
		ret = -1;
		break;
	}
	if(ret == 1)
	{
		if(len > 0)
		{	
			// 计算CRC
			out_buf[4+len]=calc_sum(out_buf+3,len+1);
			len+=5;
			out_buf[len++] = 0xC3;
			pack_len = len - 3;
			SHORT_2_BUF_BE(pack_len,(out_buf+1));
			resp_buf->wr_ptr(len);
			ACE_HEX_DUMP((LM_DEBUG,resp_buf->rd_ptr(),resp_buf->length()));
			ACE_Time_Value tv(0);
			if(peer.send_n(resp_buf,&tv) <=0 )
			{
				ACE_DEBUG((LM_ERROR,"发送应答包失败"));
				ret = -1;
			}
			else
			{
				ret = 1;
			}
		}
		else
			ret = 0;
	}
	resp_buf->release();
	return ret;
}
コード例 #16
0
ファイル: pwhash_argon2id.c プロジェクト: graydon/libsodium
int
main(void)
{
    tv();
    tv2();
    tv3();
    str_tests();

    assert(crypto_pwhash_bytes_min() > 0U);
    assert(crypto_pwhash_bytes_max() > crypto_pwhash_bytes_min());
    assert(crypto_pwhash_passwd_max() > crypto_pwhash_passwd_min());
    assert(crypto_pwhash_saltbytes() > 0U);
    assert(crypto_pwhash_strbytes() > 1U);
    assert(crypto_pwhash_strbytes() > strlen(crypto_pwhash_strprefix()));

    assert(crypto_pwhash_opslimit_min() > 0U);
    assert(crypto_pwhash_opslimit_max() > 0U);
    assert(crypto_pwhash_memlimit_min() > 0U);
    assert(crypto_pwhash_memlimit_max() > 0U);
    assert(crypto_pwhash_opslimit_interactive() > 0U);
    assert(crypto_pwhash_memlimit_interactive() > 0U);
    assert(crypto_pwhash_opslimit_moderate() > 0U);
    assert(crypto_pwhash_memlimit_moderate() > 0U);
    assert(crypto_pwhash_opslimit_sensitive() > 0U);
    assert(crypto_pwhash_memlimit_sensitive() > 0U);
    assert(strcmp(crypto_pwhash_primitive(), "argon2i") == 0);

    assert(crypto_pwhash_bytes_min() == crypto_pwhash_BYTES_MIN);
    assert(crypto_pwhash_bytes_max() == crypto_pwhash_BYTES_MAX);
    assert(crypto_pwhash_passwd_min() == crypto_pwhash_PASSWD_MIN);
    assert(crypto_pwhash_passwd_max() == crypto_pwhash_PASSWD_MAX);
    assert(crypto_pwhash_saltbytes() == crypto_pwhash_SALTBYTES);
    assert(crypto_pwhash_strbytes() == crypto_pwhash_STRBYTES);

    assert(crypto_pwhash_opslimit_min() == crypto_pwhash_OPSLIMIT_MIN);
    assert(crypto_pwhash_opslimit_max() == crypto_pwhash_OPSLIMIT_MAX);
    assert(crypto_pwhash_memlimit_min() == crypto_pwhash_MEMLIMIT_MIN);
    assert(crypto_pwhash_memlimit_max() == crypto_pwhash_MEMLIMIT_MAX);
    assert(crypto_pwhash_opslimit_interactive() ==
           crypto_pwhash_OPSLIMIT_INTERACTIVE);
    assert(crypto_pwhash_memlimit_interactive() ==
           crypto_pwhash_MEMLIMIT_INTERACTIVE);
    assert(crypto_pwhash_opslimit_moderate() ==
           crypto_pwhash_OPSLIMIT_MODERATE);
    assert(crypto_pwhash_memlimit_moderate() ==
           crypto_pwhash_MEMLIMIT_MODERATE);
    assert(crypto_pwhash_opslimit_sensitive() ==
           crypto_pwhash_OPSLIMIT_SENSITIVE);
    assert(crypto_pwhash_memlimit_sensitive() ==
           crypto_pwhash_MEMLIMIT_SENSITIVE);

    assert(crypto_pwhash_argon2id_bytes_min() == crypto_pwhash_bytes_min());
    assert(crypto_pwhash_argon2id_bytes_max() == crypto_pwhash_bytes_max());
    assert(crypto_pwhash_argon2id_passwd_min() == crypto_pwhash_passwd_min());
    assert(crypto_pwhash_argon2id_passwd_max() == crypto_pwhash_passwd_max());
    assert(crypto_pwhash_argon2id_saltbytes() == crypto_pwhash_saltbytes());
    assert(crypto_pwhash_argon2id_strbytes() == crypto_pwhash_strbytes());
    assert(strcmp(crypto_pwhash_argon2id_strprefix(),
                  crypto_pwhash_strprefix()) == 0);
    assert(crypto_pwhash_argon2id_opslimit_min() ==
           crypto_pwhash_opslimit_min());
    assert(crypto_pwhash_argon2id_opslimit_max() ==
           crypto_pwhash_opslimit_max());
    assert(crypto_pwhash_argon2id_memlimit_min() ==
           crypto_pwhash_memlimit_min());
    assert(crypto_pwhash_argon2id_memlimit_max() ==
           crypto_pwhash_memlimit_max());
    assert(crypto_pwhash_argon2id_opslimit_interactive() ==
           crypto_pwhash_opslimit_interactive());
    assert(crypto_pwhash_argon2id_opslimit_moderate() ==
           crypto_pwhash_opslimit_moderate());
    assert(crypto_pwhash_argon2id_opslimit_sensitive() ==
           crypto_pwhash_opslimit_sensitive());
    assert(crypto_pwhash_argon2id_memlimit_interactive() ==
           crypto_pwhash_memlimit_interactive());
    assert(crypto_pwhash_argon2id_memlimit_moderate() ==
           crypto_pwhash_memlimit_moderate());
    assert(crypto_pwhash_argon2id_memlimit_sensitive() ==
           crypto_pwhash_memlimit_sensitive());
    assert(crypto_pwhash_alg_argon2id13() ==
           crypto_pwhash_argon2id_alg_argon2id13());
    assert(crypto_pwhash_alg_argon2i13() == crypto_pwhash_ALG_ARGON2I13);
    assert(crypto_pwhash_alg_argon2i13() != crypto_pwhash_alg_default());
    assert(crypto_pwhash_alg_argon2id13() == crypto_pwhash_ALG_ARGON2ID13);
    assert(crypto_pwhash_alg_argon2id13() != crypto_pwhash_alg_argon2i13());
    assert(crypto_pwhash_alg_argon2id13() == crypto_pwhash_alg_default());

    assert(crypto_pwhash_argon2id(guard_page, 0, (const char *) guard_page, 0, guard_page,
                                  crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE,
                                  crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE,
                                  0) == -1);
    assert(crypto_pwhash_argon2id(guard_page, 0, (const char *) guard_page, 0, guard_page,
                                 crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE,
                                 crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE,
                                 crypto_pwhash_ALG_ARGON2I13) == -1);
    assert(crypto_pwhash_argon2i(guard_page, 0, (const char *) guard_page, 0, guard_page,
                                 crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE,
                                 crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE,
                                 0) == -1);
    assert(crypto_pwhash_argon2i(guard_page, 0, (const char *) guard_page, 0, guard_page,
                                 crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE,
                                 crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE,
                                 crypto_pwhash_ALG_ARGON2ID13) == -1);

    printf("OK\n");

    return 0;
}
コード例 #17
0
ファイル: hdsvr.cpp プロジェクト: nykma/ykt4sungard
int HDCCUSvrHandler::svc()
{
#define MES_DATA_HEAD_LEN 2

    ACE_DEBUG((LM_DEBUG,"ACE 打开连接............"));
    ACE_Message_Block * mb = NULL;

    ACE_Time_Value tv(5);
    if (this->getq(mb,&tv) == -1) return -1;
    HD8583STRUCT req;
    HD8583STRUCT resp;
    MESSAGETYPE msg_type;
    char * buffer = mb->rd_ptr();
    int len = 0;
    // 数据段长度超过允许范围,忽略请求
    if(UnPackResponseStruct(req,&msg_type,buffer,mb->length()) != 0)
    {
        ACE_ERROR((LM_ERROR,"数据包不合法"));
        mb->release();
        return -1;
    }

    ACE_HEX_DUMP((LM_DEBUG,mb->rd_ptr(),mb->length()));
    try
    {
        HDResponseHandler* handler = HDCCUProcessUnits::Instance().Create(msg_type);
        if(handler)
        {
            resp.Init();

            int result = handler->DoResponse(req,resp,peer().get_handle());
            if(result > 0)
            {
                // send back
                mb->reset();
                buffer = mb->wr_ptr();
                len = (int)PackRequestStruct(resp,msg_type,buffer,mb->size());
                mb->wr_ptr(len);
                ACE_HEX_DUMP((LM_DEBUG,buffer,mb->length()));
                ACE_DEBUG((LM_DEBUG,"数据包长度[%d]",mb->length()));
                if(peer().send_n(mb->rd_ptr(),mb->length()) <=0 )
                {
                    ACE_DEBUG((LM_ERROR,"发送应答包失败"));
                }

            }
            else if(result == 0)
            {
                // OK
                ACE_DEBUG((LM_DEBUG,"处理成功"));
            }
            else
            {
                // error
                ACE_DEBUG((LM_ERROR,"处理请求失败,返回码[%d]",result));
            }
        }
        else
        {
            ACE_ERROR((LM_ERROR,"不能处理请求代码[%c]",msg_type));
        }
    }
    catch(...)
    {
        // 捕获所有的异常
        ACE_ERROR((LM_ERROR,"处理请求异常,请求代码[%02x]",msg_type));
    }
    mb->release();
    return 0;
}
コード例 #18
0
ファイル: typecheck.c プロジェクト: KimRuneSolstad/TDT4205
data_type_t typecheck_variable(node_t* root){
	return tv(root);
}
コード例 #19
0
ファイル: optimize.cpp プロジェクト: 2bj/hhvm
bool propagate_constants(const Bytecode& op, const State& state, Gen gen) {
  auto const numPop  = op.numPop();
  auto const numPush = op.numPush();
  auto const stkSize = state.stack.size();

  // All outputs of the instruction must have constant types for this
  // to be allowed.
  for (auto i = size_t{0}; i < numPush; ++i) {
    if (!tv(state.stack[stkSize - i - 1])) return false;
  }

  // Pop the inputs, and push the constants.
  for (auto i = size_t{0}; i < numPop; ++i) {
    switch (op.popFlavor(i)) {
    case Flavor::C:  gen(bc::PopC {}); break;
    case Flavor::V:  gen(bc::PopV {}); break;
    case Flavor::A:  gen(bc::PopA {}); break;
    case Flavor::R:  not_reached();    break;
    case Flavor::F:  not_reached();    break;
    case Flavor::U:  not_reached();    break;
    }
  }

  for (auto i = size_t{0}; i < numPush; ++i) {
    auto const v = tv(state.stack[stkSize - i - 1]);
    switch (v->m_type) {
    case KindOfUninit:        not_reached();          break;
    case KindOfNull:          gen(bc::Null {});       break;
    case KindOfBoolean:
      if (v->m_data.num) {
        gen(bc::True {});
      } else {
        gen(bc::False {});
      }
      break;
    case KindOfInt64:
      gen(bc::Int { v->m_data.num });
      break;
    case KindOfDouble:
      gen(bc::Double { v->m_data.dbl });
      break;
    case KindOfStaticString:
      gen(bc::String { v->m_data.pstr });
      break;
    case KindOfArray:
      gen(bc::Array { v->m_data.parr });
      break;

    case KindOfRef:
    case KindOfResource:
    case KindOfString:
    default:
      always_assert(0 && "invalid constant in propagate_constants");
    }

    // Special case for FPass* instructions.  We just put a C on the
    // stack, so we need to get it to be an F.
    if (isFPassStar(op.op)) {
      // We should only ever const prop for FPassL right now.
      always_assert(numPush == 1 && op.op == Op::FPassL);
      gen(bc::FPassC { op.FPassL.arg1 });
    }
  }

  return true;
}
コード例 #20
0
int Expedition_Scene_Data::deserialize(Block_Buffer &r) {
	uint16_t len = 0;
	Stronghold sh;
	uint32_t ui_32 = 0;
	r.read_uint16(len);
	for (uint16_t i = 0; i < len; ++i) {
		r.read_uint32(ui_32);
		sh.deserialize(r);
		map_data_.insert(std::make_pair(ui_32, sh));
	}

	int i_32 = 0;
	int64_t i_64 = 0;
	r.read_uint16(len);
	for (uint16_t i = 0; i < len; ++i) {
		r.read_int32(i_32);
		r.read_int64(i_64);
		point_gang_id_.insert(std::make_pair(i_32, i_64));
	}
	r.read_uint32(map_base_point_num_);
	r.read_uint32(cur_line_);
	award_time_.deserialize(r);
	r.read_int32(settle_time_);

	r.read_uint16(len);
	Expedition_Occupy_Castle_Data eocd;
	for (uint16_t i = 0; i < len; ++i) {
		eocd.reset();
		eocd.deserialize(r);
		occupy_castle_rank_.insert(std::make_pair(eocd.role_id, eocd));
	}

	Expedition_Scene_Demage_Rank_Data esdrd;
	r.read_uint16(len);
	for (uint16_t i = 0; i < len; ++i) {
		esdrd.reset();
		r.read_int64(i_64);
		esdrd.deserialize(r);
		demage_rank_.insert(std::make_pair(i_64, esdrd));
	}

	Expedition_Drop_Or_Material edom;
	r.read_uint16(len);
	for (uint16_t i = 0; i < len; ++i) {
		r.read_int32(i_32);
		edom.reset();
		edom.deserialize(r);
		refreshed_drop_or_material_.insert(std::make_pair(i_32, edom));
	}

	Time_Value tv(Time_Value::zero);
	r.read_uint16(len);
	for (uint16_t i = 0; i < len; ++i) {
		r.read_int32(i_32);
		tv.deserialize(r);
		refreshed_monster_timing_[i_32] = tv;
	}

	r.read_uint16(len);
	for (uint16_t i = 0; i < len; ++i) {
		r.read_int32(i_32);
		tv.deserialize(r);
		refreshed_monster_kill_gap_[i_32] = tv;
	}

	return 0;
}
コード例 #21
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  try
  {
    // Initialize the EC Factory so we can customize the EC
    TAO_EC_Default_Factory::init_svcs ();

    // Initialize the ORB.
    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

    const ACE_TCHAR* ecname = ACE_TEXT ("EventService");
    const ACE_TCHAR* remote_ecname = 0;
    const ACE_TCHAR* iorfile = 0;
    for (int i = 0; argv[i] != 0; i++) {
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-ecname")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          ecname = argv[i];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      }
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-gateway")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          remote_ecname = argv[i];
        } else {
          std::cerr << "Missing Event channel name" << std::endl;
        }
      }
      if (ACE_OS::strcmp(argv[i], ACE_TEXT("-iorfile")) == 0) {
        if (argv[i+1] != 0) {
          i++;
          iorfile = argv[i];
        }
      }
    }

    // Get the POA
    CORBA::Object_var object = orb->resolve_initial_references ("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow (object.in ());
    PortableServer::POAManager_var poa_manager = poa->the_POAManager ();
    poa_manager->activate ();

    // Spawn a thread for the orb
    ACE_Thread_Manager *thread_mgr = ACE_Thread_Manager::instance();
    thread_mgr->spawn(orb_thread, orb.in());

    // Create a local event channel and register it with the RootPOA.
    TAO_EC_Event_Channel_Attributes attributes (poa.in (), poa.in ());
    PortableServer::Servant_var<TAO_EC_Event_Channel> ec_impl =
      new TAO_EC_Event_Channel(attributes);
    ec_impl->activate ();
    PortableServer::ObjectId_var oid = poa->activate_object(ec_impl.in());
    CORBA::Object_var ec_obj = poa->id_to_reference(oid.in());
    RtecEventChannelAdmin::EventChannel_var ec =
      RtecEventChannelAdmin::EventChannel::_narrow(ec_obj.in());

    // Find the Naming Service.
    object = orb->resolve_initial_references("NameService");
    CosNaming::NamingContextExt_var root_context = CosNaming::NamingContextExt::_narrow(object.in());
    CosNaming::Name_var name = root_context->to_name (ACE_TEXT_ALWAYS_CHAR (ecname));
    root_context->rebind(name.in(), ec.in());

    // Get a SupplierAdmin object from the EventChannel.
    RtecEventChannelAdmin::SupplierAdmin_var admin = ec->for_suppliers();

    // Get a ProxyPushConsumer from the SupplierAdmin.
    RtecEventChannelAdmin::ProxyPushConsumer_var consumer =
                                        admin->obtain_push_consumer();

    // Instantiate an EchoEventSupplier_i servant.
    PortableServer::Servant_var<EchoEventSupplier_i> servant =
      new EchoEventSupplier_i(orb.in());

    // Register it with the RootPOA.
    oid = poa->activate_object(servant.in());
    CORBA::Object_var supplier_obj = poa->id_to_reference(oid.in());
    RtecEventComm::PushSupplier_var supplier =
      RtecEventComm::PushSupplier::_narrow(supplier_obj.in());

    // Publish the events the supplier provides.
    ACE_SupplierQOS_Factory qos;
    qos.insert (MY_SOURCE_ID,      // Supplier's unique id
                MY_EVENT_TYPE,     // Event type
                0,                 // handle to the rt_info structure
                1);                // number of calls

    // Connect as a supplier of the published events.
    consumer->connect_push_supplier (supplier.in (),
                                     qos.get_SupplierQOS ());

    // Create an event (just a string in this case).
    const CORBA::String_var eventData = CORBA::string_dup (ACE_TEXT_ALWAYS_CHAR (ecname));

    // Create an event set for one event
    RtecEventComm::EventSet event (1);
    event.length (1);
    // Initialize event header.
    event[0].header.source = MY_SOURCE_ID;
    event[0].header.ttl = 1;
    event[0].header.type = MY_EVENT_TYPE;
    // Initialize data fields in event.
    event[0].data.any_value <<= eventData;

    PortableServer::Servant_var<TAO_EC_Gateway_IIOP> gateway =
      new TAO_EC_Gateway_IIOP;
    int gateway_initialized = 0;

    std::cout << "Supplier starting sending of events.\n";

    while (1) {

      consumer->push (event);
      ACE_Time_Value tv(0, 1000 * EVENT_DELAY_MS);
      orb->run(tv);

      if ((remote_ecname != 0)  && (!gateway_initialized)) {

        try {
          // Get the remote event channel object
          CORBA::Object_var obj = root_context->resolve_str (ACE_TEXT_ALWAYS_CHAR (remote_ecname));
          RtecEventChannelAdmin::EventChannel_var remote_ec =
            RtecEventChannelAdmin::EventChannel::_narrow(obj.in());

          int ok = 0;
          if (!CORBA::is_nil(remote_ec.in())) {
            // Now check if we can talk to it...
            try {
              RtecEventChannelAdmin::SupplierAdmin_var adm =
                remote_ec->for_suppliers();
              ok = 1;
            } catch(const CORBA::UserException&) {
              // What is the correct exception(s) to catch here?
            }
          }

          // There is a good remote event channel so initialize the
          // gateway.
          if (ok) {
            gateway->init(remote_ec.in(), ec.in());

            PortableServer::ObjectId_var gateway_oid =
              poa->activate_object(gateway.in());
            CORBA::Object_var gateway_obj =
              poa->id_to_reference(gateway_oid.in());
            RtecEventChannelAdmin::Observer_var obs =
              RtecEventChannelAdmin::Observer::_narrow(gateway_obj.in());
            RtecEventChannelAdmin::Observer_Handle local_ec_obs_handle =
              ec->append_observer (obs.in ());
            ACE_UNUSED_ARG (local_ec_obs_handle);
            gateway_initialized = 1;
            std::cout << "Gateway initialized\n";
            if (iorfile != 0) {
              CORBA::String_var str = orb->object_to_string( ec.in() );
              std::ofstream iorFile( ACE_TEXT_ALWAYS_CHAR(iorfile) );
              iorFile << str.in() << std::endl;
              iorFile.close();
            }
          }
        } catch(const CosNaming::NamingContext::NotFound&) {
          // Try again later...
        }
      }
    }

    orb->destroy();

    return 0;
  }
  catch(const CORBA::Exception& exc)
  {
    std::cerr << "Caught CORBA::Exception" << std::endl << exc << std::endl;
  }

  return 1;
}
コード例 #22
0
void
OpenDDS::DCPS::SimpleTcpDataLink::fully_associated()
{
  DBG_ENTRY_LVL("SimpleTcpDataLink","fully_associated",6);

  while (!this->connection_->is_connected()) {
    ACE_Time_Value tv(0, 100000);
    ACE_OS::sleep(tv);
  }

  this->resume_send();
  bool swap_byte = this->transport_->get_configuration()->swap_bytes_;
  DataSampleHeader header_data;
  // The message_id_ is the most important value for the DataSampleHeader.
  header_data.message_id_ = FULLY_ASSOCIATED;

  // Other data in the DataSampleHeader are not necessary set. The bogus values
  // can be used.

  header_data.byte_order_
  = swap_byte ? !TAO_ENCAP_BYTE_ORDER : TAO_ENCAP_BYTE_ORDER;
  //header_data.message_length_ = 0;
  //header_data.sequence_ = 0;
  //DDS::Time_t source_timestamp
  //  = OpenDDS::DCPS::time_value_to_time (ACE_OS::gettimeofday ());
  //header_data.source_timestamp_sec_ = source_timestamp.sec;
  //header_data.source_timestamp_nanosec_ = source_timestamp.nanosec;
  //header_data.coherency_group_ = 0;
  //header_data.publication_id_ = 0;

  ACE_Message_Block* message;
  size_t max_marshaled_size = header_data.max_marshaled_size();

  ACE_Message_Block* data = this->marshal_acks(swap_byte);

  header_data.message_length_ = data->length();

  ACE_NEW(message,
          ACE_Message_Block(max_marshaled_size,
                            ACE_Message_Block::MB_DATA,
                            data, //cont
                            0, //data
                            0, //allocator_strategy
                            0, //locking_strategy
                            ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY,
                            ACE_Time_Value::zero,
                            ACE_Time_Value::max_time,
                            0,
                            0));

  message << header_data;

  TransportControlElement* send_element = 0;

  ACE_NEW(send_element, TransportControlElement(message));

  // give the message block ownership to TransportControlElement
  message->release ();

  this->send_i(send_element);
}
コード例 #23
0
ファイル: cg_effects.c プロジェクト: DerSaidin/OpenWolf
/*
==============
CG_LoseHat
==============
*/
void CG_LoseHat(centity_t * cent, vec3_t dir)
{
	clientInfo_t   *ci;
	int             clientNum;

//  int             i, count, tagIndex, gibIndex;
	int             tagIndex;
	vec3_t          origin, velocity;
	bg_character_t *character;

	clientNum = cent->currentState.clientNum;
	if(clientNum < 0 || clientNum >= MAX_CLIENTS)
	{
		CG_Error("Bad clientNum on player entity");
	}
	ci = &cgs.clientinfo[clientNum];
	character = CG_CharacterForClientinfo(ci, cent);

	// don't launch anything if they don't have one
	if(!character->accModels[ACC_HAT])
	{
		return;
	}

	tagIndex = CG_GetOriginForTag(cent, &cent->pe.headRefEnt, "tag_mouth", 0, origin, NULL);

	velocity[0] = dir[0] * (0.75 + random()) * GIB_VELOCITY;
	velocity[1] = dir[1] * (0.75 + random()) * GIB_VELOCITY;
	velocity[2] = GIB_JUMP - 50 + dir[2] * (0.5 + random()) * GIB_VELOCITY;

	{
		localEntity_t  *le;
		refEntity_t    *re;

		le = CG_AllocLocalEntity();
		re = &le->refEntity;

		le->leType = LE_FRAGMENT;
		le->startTime = cg.time;
		le->endTime = le->startTime + 20000 + (crandom() * 5000);

		VectorCopy(origin, re->origin);
		AxisCopy(axisDefault, re->axis);
		re->hModel = character->accModels[ACC_HAT];
		re->customSkin = character->accSkins[ACC_HAT];

		re->fadeStartTime = le->endTime - 1000;
		re->fadeEndTime = le->endTime;

		// (SA) FIXME: origin of hat md3 is offset from center.  need to center the origin when you toss it
		le->pos.trType = TR_GRAVITY;
		VectorCopy(origin, le->pos.trBase);
		VectorCopy(velocity, le->pos.trDelta);
		le->pos.trTime = cg.time;

		// spin it a bit
		le->angles.trType = TR_LINEAR;
		VectorCopy(tv(0, 0, 0), le->angles.trBase);
		le->angles.trDelta[0] = 0;
		le->angles.trDelta[1] = (100 + (rand() & 500)) - 300;
//      le->angles.trDelta[2]   = 0;
		le->angles.trDelta[2] = 400;	// (SA) this is set with a very particular value to try to get it
		// to flip exactly once before landing (based on player alive
		// (standing) and on level ground) and will be unnecessary when
		// I have things landing properly on their own

		le->angles.trTime = cg.time;

		le->bounceFactor = 0.2;

		// Ridah, if the player is on fire, then make the hat on fire
		if(cent && CG_EntOnFire(cent))
		{
			le->onFireStart = cent->currentState.onFireStart;
			le->onFireEnd = cent->currentState.onFireEnd + 4000;
		}
	}
}
コード例 #24
0
ファイル: ai_nodes.c プロジェクト: mylemans/vrxcl
//==========================================
// AI_PredictJumpadDestity
// Make a guess on where a jumpad will send
// the player.
//==========================================
qboolean AI_PredictJumpadDestity( edict_t *ent, vec3_t out )
{
	int		i;
	edict_t *target;
	trace_t	trace;
	vec3_t	pad_origin, v1, v2;
	float	htime, vtime, tmpfloat, player_factor;	//player movement guess
	vec3_t	floor_target_origin, target_origin;
	vec3_t	floor_dist_vec, floor_movedir;

	VectorClear( out );

	if( !ent->target )	//jabot092
		return false;

	// get target entity
	target = G_Find ( NULL, FOFS(targetname), ent->target );
	if (!target)
		return false;

	// find pad origin
	VectorCopy( ent->maxs, v1 );
	VectorCopy( ent->mins, v2 );
	pad_origin[0] = (v1[0] - v2[0]) / 2 + v2[0];
	pad_origin[1] = (v1[1] - v2[1]) / 2 + v2[1];
	pad_origin[2] = ent->maxs[2];

	//make a projection 'on floor' of target origin
	VectorCopy( target->s.origin, target_origin );
	VectorCopy( target->s.origin, floor_target_origin );
	floor_target_origin[2] = pad_origin[2];	//put at pad's height

	//make a guess on how player movement will affect the trajectory
	tmpfloat = AI_Distance( pad_origin, floor_target_origin );
	htime = sqrt ((tmpfloat));
	vtime = sqrt ((target->s.origin[2] - pad_origin[2]));
	if(!vtime) return false;
	htime *= 4;vtime *= 4;
	if( htime > vtime )
		htime = vtime;
	player_factor = vtime - htime;

	// find distance vector, on floor, from pad_origin to target origin.
	for ( i=0 ; i<3 ; i++ )
		floor_dist_vec[i] = floor_target_origin[i] - pad_origin[i];

	// movement direction on floor
	VectorCopy( floor_dist_vec, floor_movedir );
	VectorNormalize( floor_movedir );

	// move both target origin and target origin on floor by player movement factor.
	VectorMA ( target_origin, player_factor, floor_movedir, target_origin);
	VectorMA ( floor_target_origin, player_factor, floor_movedir, floor_target_origin);

	// move target origin on floor by floor distance, and add another player factor step to it
	VectorMA ( floor_target_origin, 1, floor_dist_vec, floor_target_origin);
	VectorMA ( floor_target_origin, player_factor, floor_movedir, floor_target_origin);

#ifdef SHOW_JUMPAD_GUESS
	// this is our top of the curve point, and the original target
	AI_JumpadGuess_ShowPoint( target_origin, "models/powerups/health/mega_sphere.md3" );
	AI_JumpadGuess_ShowPoint( target->s.origin, "models/powerups/health/large_cross.md3" );
#endif

	//trace from target origin to endPoint.
//	trap_Trace ( &trace, target_origin, tv(-15, -15, -8), tv(15, 15, 8), floor_target_origin, NULL, MASK_NODESOLID);
	trace = gi.trace(  target_origin, tv(-15, -15, -8), tv(15, 15, 8), floor_target_origin, NULL, MASK_NODESOLID);
	if (trace.fraction == 1.0 && trace.startsolid || trace.allsolid && trace.startsolid){
//		G_Printf("JUMPAD LAND: ERROR: trace was in solid.\n"); //started inside solid (target should never be inside solid, this is a mapper error)
		return false;
	} else if ( trace.fraction == 1.0 ) {
		
		//didn't find solid. Extend Down (I have to improve this part)
		vec3_t	target_origin2, extended_endpoint, extend_dist_vec;
		
		VectorCopy( floor_target_origin, target_origin2 );
		for ( i=0 ; i<3 ; i++ )
			extend_dist_vec[i] = floor_target_origin[i] - target_origin[i];
		
		VectorMA ( target_origin2, 1, extend_dist_vec, extended_endpoint);
		//repeat tracing
//		trap_Trace ( &trace, target_origin2, tv(-15, -15, -8), tv(15, 15, 8), extended_endpoint, NULL, MASK_NODESOLID);
		trace = gi.trace(  target_origin2, tv(-15, -15, -8), tv(15, 15, 8), extended_endpoint, NULL, MASK_NODESOLID);
		if ( trace.fraction == 1.0 )
			return false;//still didn't find solid
	}
	
#ifdef SHOW_JUMPAD_GUESS
	// destiny found
	AI_JumpadGuess_ShowPoint( trace.endpos, "models/powerups/health/mega_sphere.md3" );
#endif

	VectorCopy ( trace.endpos, out );
	return true;
}
コード例 #25
0
ファイル: qilog.cpp プロジェクト: soshiant1992/libqi
int subCmd_logSend(int argc, char **argv, qi::ApplicationSession& app)
{
  po::options_description   desc("Usage: qicli log-send <message>");

  desc.add_options()
      ("help,h", "Print this help message and exit")
      ("verbose,v", "Set sent message verbosity to verbose.")
      ("debug,d", "Set sent message verbosity to debug.")
      ("level,l", po::value<int>()->default_value(4), "Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.")
      ("category,c", po::value<std::string>(), "Message's category (default: \"qicli.qilog.logsend\").")
      ("message,m", po::value<std::string>(), "Message to send.")
      ;

  po::positional_options_description positionalOptions;
  positionalOptions.add("message", -1);

  po::variables_map vm;
  if (!poDefault(po::command_line_parser(argc, argv)
                 .options(desc).positional(positionalOptions), vm, desc))
    return 1;

  qiLogVerbose() << "Connecting to service directory";
  app.start();
  qi::SessionPtr s = app.session();

  qiLogVerbose() << "Resolving services";

  qi::AnyObject logger = s->service("LogManager");

  qi::os::timeval tv(qi::SystemClock::now());

  std::string source(__FILE__);
  source += ':';
  source += __FUNCTION__;
  source += ':';
  source += boost::lexical_cast<std::string>(__LINE__);

  int level = 4;
  if (vm.count("level"))
  {
    level = vm["level"].as<int>();

    if (level > 6)
      level =  6;
    else if (level <= 0)
      level = 0;
  }
  if (vm.count("verbose"))
    level = 5;

  if (vm.count("debug"))
    level = 6;

  std::string category = "qicli.qilog.logsend";
  if (vm.count("category"))
    category = vm["category"].as<std::string>();

  std::string location = qi::os::getMachineId() + ":" + boost::lexical_cast<std::string>(qi::os::getpid());;
  std::string message = "";
  if (vm.count("message"))
    message = vm["message"].as<std::string>();

  // timestamp
  qi::AnyReferenceVector timeVectRef;
  timeVectRef.push_back(qi::AnyReference::from(tv.tv_sec));
  timeVectRef.push_back(qi::AnyReference::from(tv.tv_usec));
  qi::AnyValue timeVal = qi::AnyValue::makeTuple(timeVectRef);

  qi::AnyReferenceVector msgVectRef;
  msgVectRef.push_back(qi::AnyReference::from(source));
  msgVectRef.push_back(qi::AnyReference::from(level));
  msgVectRef.push_back(timeVal.asReference()); //timestamp
  msgVectRef.push_back(qi::AnyReference::from(category));
  msgVectRef.push_back(qi::AnyReference::from(location));
  msgVectRef.push_back(qi::AnyReference::from(message));
  msgVectRef.push_back(qi::AnyReference::from(0));

  std::vector<qi::AnyValue> msgs;
  msgs.push_back(qi::AnyValue::makeTuple(msgVectRef));
  logger.call<void>("log", qi::AnyValue::from(msgs));

  logger.reset();

  return 0;
}
コード例 #26
0
ファイル: devnode.cpp プロジェクト: nykma/ykt4sungard
	int LoopDeviceSvcHandler::RecvRequest(int *pRet,KSG_GW_PACK_t* gw_pack)
	{
		KSG_GW_PACK_t* req;
		request_pack* pack;
		int ret;
		ACE_Message_Block * mb = NULL;
		ACE_Time_Value tv(5);
		tv += ACE_OS::gettimeofday();
		ret = this->getq(mb,&tv);
		ACE_ASSERT((ret != -1));
		ACE_DEBUG((LM_DEBUG,"处理业务请求"));
		if(!mb)
		{
			ACE_DEBUG((LM_ERROR,"未从消息队列中获取数据包[%d]",ret));
			return -1;
		}
		req = (KSG_GW_PACK_t*)mb->rd_ptr();
		if(UnPackData(req))
		{
			ACE_DEBUG((LM_DEBUG,"解压数据包失败"));
			return -1;
		}
		memcpy(gw_pack,req,sizeof(KSG_GW_PACK_t));
		ret = -1;
		ACE_DEBUG((LM_DEBUG,"处理第[%d]个数据包,后续包标志[%d]",req->pack_index
			,req->next_pack));
		
		if((pack = (request_pack*)ACE_OS::malloc(sizeof(request_pack))) == NULL)
		{
			ACE_ERROR_RETURN((LM_ERROR,"申请内存失败"),-1);
		}
		try
		{
			ACE_OS::memset(pack,0,sizeof pack);
			pack->datalen = req->length;
			memcpy(pack->data,req->data,pack->datalen);
			*pRet = KSGLoopDeviceListenScheduler::_s_interface.ProcessRequest(
				req->func_no,pack);
			if(pack->outdatalen >= sizeof(pack->outdata))
			{
				ACE_DEBUG((LM_ERROR,"业务层返回数据包错误"));
				*pRet = KSG_LI_INTERNAL_ERROR;
			}
			else if(*pRet != 0)
			{
				pack->outdata[pack->outdatalen] = 0;
				ACE_DEBUG((LM_DEBUG,"处理请求失败[%d][%s]",*pRet,pack->outdata));
			}
			// 应答
			if(SendResponse(*pRet,req,pack))
			{
				ACE_DEBUG((LM_ERROR,"发送应答数据包失败"));
			}
			else
				ret = 0;
		}
		catch(...)
		{
			ACE_DEBUG((LM_ERROR,"请求处理异常!!!"));
			//
		}
		mb->release();
		ACE_OS::free(pack);
		return ret;
	}
コード例 #27
0
ファイル: g_awards.cpp プロジェクト: cfr/qfusion
void G_AwardPlayerKilled( edict_t *self, edict_t *inflictor, edict_t *attacker, int mod )
{
	trace_t trace;
	score_stats_t *stats;
	loggedFrag_t *lfrag;

	if( self->r.svflags & SVF_CORPSE )
		return;

	if( !attacker->r.client )
		return;

	if( !self->r.client )
		return;

	if( attacker == self )
		return;

	if( attacker->s.team == self->s.team && attacker->s.team > TEAM_PLAYERS )
		return;

	if( mod == MOD_ROCKET_W || mod == MOD_ROCKET_S )
	{
		// direct hit
		attacker->r.client->resp.awardInfo.directrocket_count++;
		if( attacker->r.client->resp.awardInfo.directrocket_count == DIRECTROCKET_FOR_AWARD )
		{
			attacker->r.client->resp.awardInfo.directrocket_count = 0;
			attacker->r.client->resp.awardInfo.directrocket_award++;
			G_PlayerAward( attacker, S_COLOR_BLUE "Direct Rocket Hit!" );
		}
		// Midair
		if( self->groundentity == NULL && !self->waterlevel )
		{
			// check for height to the ground
			G_Trace( &trace, self->s.origin, self->r.mins, self->r.maxs, tv( self->s.origin[0], self->s.origin[1], self->s.origin[2] - 64 ), self, MASK_SOLID );
			if( trace.fraction == 1.0f )
			{
				attacker->r.client->resp.awardInfo.rl_midair_award++;
				G_PlayerAward( attacker, S_COLOR_BLUE "Air Rocket!" );
			}
		}
	}
	if( mod == MOD_GRENADE_W || mod == MOD_GRENADE_S )
	{
		// direct hit
		attacker->r.client->resp.awardInfo.directgrenade_count++;
		if( attacker->r.client->resp.awardInfo.directgrenade_count == DIRECTGRENADE_FOR_AWARD )
		{
			attacker->r.client->resp.awardInfo.directgrenade_count = 0;
			attacker->r.client->resp.awardInfo.directgrenade_award++;
			G_PlayerAward( attacker, S_COLOR_BLUE "Direct Grenade Hit!" );
		}

		// Midair
		if( self->groundentity == NULL && !self->waterlevel )
		{
			// check for height to the ground
			G_Trace( &trace, self->s.origin, self->r.mins, self->r.maxs, tv( self->s.origin[0], self->s.origin[1], self->s.origin[2] - 64 ), self, MASK_SOLID );
			if( trace.fraction == 1.0f )
			{
				attacker->r.client->resp.awardInfo.gl_midair_award++;
				G_PlayerAward( attacker, S_COLOR_BLUE "Air Grenade!" );
			}
		}
	}

	// Multikill
	if( game.serverTime - attacker->r.client->resp.awardInfo.multifrag_timer < MULTIKILL_INTERVAL )
		attacker->r.client->resp.awardInfo.multifrag_count++;
	else
		attacker->r.client->resp.awardInfo.multifrag_count = 1;

	attacker->r.client->resp.awardInfo.multifrag_timer = game.serverTime;

	if( attacker->r.client->resp.awardInfo.multifrag_count > 1 )
	{
		char s[MAX_CONFIGSTRING_CHARS];

		s[0] = 0;

		switch( attacker->r.client->resp.awardInfo.multifrag_count )
		{
		case 0:
		case 1:
			break;
		case 2:
			Q_strncpyz( s, S_COLOR_GREEN "Double Frag!", sizeof( s ) );
			break;
		case 3:
			Q_strncpyz( s, S_COLOR_GREEN "Triple Frag!", sizeof( s ) );
			break;
		case 4:
			Q_strncpyz( s, S_COLOR_GREEN "Quadruple Frag!", sizeof( s ) );
			break;
		default:
			Q_snprintfz( s, sizeof( s ), S_COLOR_GREEN "Extermination! %i in a row!", attacker->r.client->resp.awardInfo.multifrag_count );
			break;
		}

		G_PlayerAward( attacker, s );
	}

	// Sprees
	attacker->r.client->resp.awardInfo.frag_count++;

	if( attacker->r.client->resp.awardInfo.frag_count &&
		( attacker->r.client->resp.awardInfo.frag_count % 5 == 0 ) )
	{
		char s[MAX_CONFIGSTRING_CHARS];

		s[0] = 0;

		switch( (int)( attacker->r.client->resp.awardInfo.frag_count / 5 ) )
		{
		case 1:
			Q_strncpyz( s, S_COLOR_YELLOW "On Fire!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is On Fire!\n", attacker->r.client->netname );
			break;
		case 2:
			Q_strncpyz( s, S_COLOR_YELLOW "Raging!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is Raging!\n", attacker->r.client->netname );
			break;
		case 3:
			Q_strncpyz( s, S_COLOR_YELLOW "Fraglord!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is the Fraglord!\n", attacker->r.client->netname );
			break;
		case 4:
			Q_strncpyz( s, S_COLOR_YELLOW "Extermination!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is Exterminating!\n", attacker->r.client->netname );
			break;
		default:
			Q_strncpyz( s, S_COLOR_YELLOW "God Mode!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is in God Mode!\n", attacker->r.client->netname );
			break;
		}

		G_PlayerAward( attacker, s );
	}

	if( teamlist[attacker->s.team].stats.frags == 1 )
	{
		int i;

		for( i = TEAM_PLAYERS; i < GS_MAX_TEAMS; i++ ) {
			if( i == attacker->s.team )
				continue;
			if( teamlist[i].stats.frags )
				break;
		}

		if( i != GS_MAX_TEAMS )
			G_PlayerAward( attacker, S_COLOR_YELLOW "First Frag!" );
	}

	// ch : weapon specific frags
	if ( G_ModToAmmo( mod ) != AMMO_NONE )
		attacker->r.client->level.stats.accuracy_frags[G_ModToAmmo( mod )-AMMO_GUNBLADE]++;

	if( GS_MatchState() == MATCH_STATE_PLAYTIME /* && !strcmp( "duel", gs.gametypeName ) */)
	{
		// ch : frag log
		stats = &attacker->r.client->level.stats;
		if( !stats->fragAllocator )
			stats->fragAllocator = LinearAllocator( sizeof( loggedFrag_t ), 0, _G_LevelMalloc, _G_LevelFree );

		lfrag = ( loggedFrag_t * )LA_Alloc( stats->fragAllocator );
		lfrag->mm_attacker = attacker->r.client->mm_session;
		lfrag->mm_victim = self->r.client->mm_session;
		lfrag->weapon = G_ModToAmmo( mod ) - AMMO_GUNBLADE;
		lfrag->time = ( game.serverTime - GS_MatchStartTime() ) / 1000;
	}
}
コード例 #28
0
ファイル: g_awards.c プロジェクト: Racenet/racesow
void G_AwardPlayerKilled( edict_t *self, edict_t *inflictor, edict_t *attacker, int mod )
{
	trace_t trace;

	if( self->r.svflags & SVF_CORPSE )
		return;

	if( !attacker->r.client )
		return;

	if( !self->r.client )
		return;

	if( attacker == self )
		return;

	if( attacker->s.team == self->s.team && attacker->s.team > TEAM_PLAYERS )
		return;

	if( mod == MOD_ROCKET_W || mod == MOD_ROCKET_S )
	{
		// direct hit
		attacker->r.client->resp.awardInfo.directrocket_count++;
		if( attacker->r.client->resp.awardInfo.directrocket_count == DIRECTROCKET_FOR_AWARD )
		{
			attacker->r.client->resp.awardInfo.directrocket_count = 0;
			attacker->r.client->resp.awardInfo.directrocket_award++;
			G_PlayerAward( attacker, S_COLOR_BLUE "Direct Rocket Hit!" );
		}
		// Midair
		if( self->groundentity == NULL && !self->waterlevel )
		{
			// check for height to the ground
			G_Trace( &trace, self->s.origin, self->r.mins, self->r.maxs, tv( self->s.origin[0], self->s.origin[1], self->s.origin[2] - 64 ), self, MASK_SOLID );
			if( trace.fraction == 1.0f )
			{
				attacker->r.client->resp.awardInfo.rl_midair_award++;
				G_PlayerAward( attacker, S_COLOR_BLUE "Air Rocket!" );
			}
		}
	}
	if( mod == MOD_GRENADE_W || mod == MOD_GRENADE_S )
	{
		// direct hit
		attacker->r.client->resp.awardInfo.directgrenade_count++;
		if( attacker->r.client->resp.awardInfo.directgrenade_count == DIRECTGRENADE_FOR_AWARD )
		{
			attacker->r.client->resp.awardInfo.directgrenade_count = 0;
			attacker->r.client->resp.awardInfo.directgrenade_award++;
			G_PlayerAward( attacker, S_COLOR_BLUE "Direct Grenade Hit!" );
		}

		// Midair
		if( self->groundentity == NULL && !self->waterlevel )
		{
			// check for height to the ground
			G_Trace( &trace, self->s.origin, self->r.mins, self->r.maxs, tv( self->s.origin[0], self->s.origin[1], self->s.origin[2] - 64 ), self, MASK_SOLID );
			if( trace.fraction == 1.0f )
			{
				attacker->r.client->resp.awardInfo.gl_midair_award++;
				G_PlayerAward( attacker, S_COLOR_BLUE "Air Grenade!" );
			}
		}
	}

	// Multikill
	if( game.serverTime - attacker->r.client->resp.awardInfo.multifrag_timer < MULTIKILL_INTERVAL )
		attacker->r.client->resp.awardInfo.multifrag_count++;
	else
		attacker->r.client->resp.awardInfo.multifrag_count = 1;

	attacker->r.client->resp.awardInfo.multifrag_timer = game.serverTime;

	if( attacker->r.client->resp.awardInfo.multifrag_count > 1 )
	{
		char s[MAX_CONFIGSTRING_CHARS];

		s[0] = 0;

		switch( attacker->r.client->resp.awardInfo.multifrag_count )
		{
		case 0:
		case 1:
			break;
		case 2:
			Q_strncpyz( s, S_COLOR_GREEN "Double Frag!", sizeof( s ) );
			break;
		case 3:
			Q_strncpyz( s, S_COLOR_GREEN "Triple Frag!", sizeof( s ) );
			break;
		case 4:
			Q_strncpyz( s, S_COLOR_GREEN "Quadruple Frag!", sizeof( s ) );
			break;
		default:
			Q_snprintfz( s, sizeof( s ), S_COLOR_GREEN "Extermination! %i in a row!", attacker->r.client->resp.awardInfo.multifrag_count );
			break;
		}

		G_PlayerAward( attacker, s );
	}

	// Sprees
	attacker->r.client->resp.awardInfo.frag_count++;

	if( attacker->r.client->resp.awardInfo.frag_count &&
		( attacker->r.client->resp.awardInfo.frag_count % 5 == 0 ) )
	{
		char s[MAX_CONFIGSTRING_CHARS];

		s[0] = 0;

		switch( (int)( attacker->r.client->resp.awardInfo.frag_count / 5 ) )
		{
		case 1:
			Q_strncpyz( s, S_COLOR_YELLOW "On Fire!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is On Fire!\n", attacker->r.client->netname );
			break;
		case 2:
			Q_strncpyz( s, S_COLOR_YELLOW "Raging!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is Raging!\n", attacker->r.client->netname );
			break;
		case 3:
			Q_strncpyz( s, S_COLOR_YELLOW "Fraglord!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is the Fraglord!\n", attacker->r.client->netname );
			break;
		case 4:
			Q_strncpyz( s, S_COLOR_YELLOW "Extermination!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is Exterminating!\n", attacker->r.client->netname );
			break;
		default:
			Q_strncpyz( s, S_COLOR_YELLOW "God Mode!", sizeof( s ) );
			G_PrintMsg( NULL, "%s" S_COLOR_YELLOW " is in God Mode!\n", attacker->r.client->netname );
			break;
		}

		G_PlayerAward( attacker, s );
	}
}
コード例 #29
0
void SoCapsule::build ( float len, float rt, float rb, int nfaces )
{
    P.clear(); C.clear(); // set size to zero, just in case
   
    float hlen = len/2.0f;
    int   levels = std::ceil(static_cast<float>(nfaces) / 2.0f);
    float faceAngularHeight = (static_cast<float>(M_PI) / 2.0) / static_cast<float>(levels);
    float faceAngularLength = (2.0 * static_cast<float>(M_PI)) / static_cast<float>(nfaces);
    int   vertices = 2 + (2*levels + 1)*(nfaces * 6);

    // Reserve space for the capsule vertices
    P.reserve(vertices);
    C.reserve(vertices);

    // Generate the coordinates for the capsule body
    std::vector<GsVec> bodyTopCoordinates;
    std::vector<GsVec> bodyBottomCoordinates;
    bodyTopCoordinates.reserve(nfaces);
    bodyBottomCoordinates.reserve(nfaces);

    // Compute the tube section of the capsule
    for(int i = 0; i < nfaces; i++)
    {
        float p = static_cast<float>(i) * faceAngularLength;
        
        bodyTopCoordinates.push_back(GsVec(rt * std::cos(p), hlen, rt * std::sin(p)));
        bodyBottomCoordinates.push_back(GsVec(rb * std::cos(p), -hlen, rb * std::sin(p)));
    }
    pushLevel(P, C, bodyTopCoordinates, bodyBottomCoordinates, nfaces);

    // Compute the top of the capsule
    std::vector<GsVec>& previousTopVector = bodyTopCoordinates;
    std::vector<GsVec>  currentTopVector;
    currentTopVector.reserve(nfaces);

    for(int j = 1; j < levels; j++)
    {
        // theta coordinate
        float t = static_cast<float>(j) * faceAngularHeight;
        for(int i = 0; i < nfaces; i++)
        {
            // phi coordinate
            float p = static_cast<float>(i) * faceAngularLength;
            currentTopVector.push_back(GsVec((rt * std::cos(p)) * std::cos(t), 
                                             hlen + (rt * std::sin(t)), 
                                             (rt * std::sin(p)) * std::cos(t)));

        }
        pushLevel(P, C, currentTopVector, previousTopVector, nfaces);

        std::swap(currentTopVector, previousTopVector);
        currentTopVector.clear();
    }

    // Compute the cap of the capsule
    GsVec tv(0.0f, hlen + rt, 0.0f);
    for(int i = 0; i < nfaces; i++)
    {
        GsVec a = previousTopVector[i];
        GsVec b = (i+1 == nfaces) ? previousTopVector[0] : previousTopVector[i+1];

        pushTriangle(P, C, {a, b, tv});
    }

    // Compute the bottom of the capsule
    std::vector<GsVec>& previousBottomVector = bodyBottomCoordinates;
    std::vector<GsVec>  currentBottomVector;
    currentBottomVector.reserve(nfaces);
    
    for(int j = 1; j < levels; j++)
    {
        // theta coordinate
        float t = static_cast<float>(j) * faceAngularHeight;
        for(int i = 0; i < nfaces; i++)
        {
            // phi coordinate
            float p = static_cast<float>(i) * faceAngularLength;
            currentBottomVector.push_back(GsVec((rb * std::cos(p)) * std::cos(t), 
                                                -hlen - (rb * std::sin(t)), 
                                                (rb * std::sin(p)) * std::cos(t)));

        }
        pushLevel(P, C, currentBottomVector, previousBottomVector, nfaces);

        std::swap(currentBottomVector, previousBottomVector);
        currentBottomVector.clear();
    }

    // Compute the cap of the capsule
    GsVec bv(0.0f, -hlen - rb, 0.0f);
    for(int i = 0; i < nfaces; i++)
    {
        GsVec a = previousBottomVector[i];
        GsVec b = (i+1 == nfaces) ? previousBottomVector[0] : previousBottomVector[i+1];

        pushTriangle(P, C, {a, bv, b});
    }
    //pushCap(P, C, previousBottomVector, bv, nfaces);

    // send data to OpenGL buffers:
    glBindBuffer ( GL_ARRAY_BUFFER, buf[0] );
    glBufferData ( GL_ARRAY_BUFFER, P.size()*3*sizeof(float), &P[0], GL_STATIC_DRAW );
    glBindBuffer ( GL_ARRAY_BUFFER, buf[1] );
    glBufferData ( GL_ARRAY_BUFFER, C.size()*4*sizeof(gsbyte), &C[0], GL_STATIC_DRAW );
    
    // save size so that we can free our buffers and later just draw the OpenGL arrays:
    _numpoints = P.size();
    
    // free non-needed memory:
    P.resize(0); C.resize(0);
    changed = 0;
}
コード例 #30
0
ファイル: pwhash.c プロジェクト: BatikhSouri/node-sodium
int main(void)
{
    char       *str_out;
    char       *str_out2;
    char       *salt;
    const char *passwd = "Correct Horse Battery Staple";

    tv();
    tv2();
    tv3();
    salt = (char *)
        sodium_malloc(crypto_pwhash_scryptsalsa208sha256_SALTBYTES);
    str_out = (char *)
        sodium_malloc(crypto_pwhash_scryptsalsa208sha256_STRBYTES);
    str_out2 = (char *)
        sodium_malloc(crypto_pwhash_scryptsalsa208sha256_STRBYTES);
    memcpy(salt, "[<~A 32-bytes salt for scrypt~>]",
           crypto_pwhash_scryptsalsa208sha256_SALTBYTES);
    if (crypto_pwhash_scryptsalsa208sha256_str(str_out, passwd, strlen(passwd),
                                               OPSLIMIT, MEMLIMIT) != 0) {
        printf("pwhash_str failure\n");
    }
    if (crypto_pwhash_scryptsalsa208sha256_str(str_out2, passwd, strlen(passwd),
                                               OPSLIMIT, MEMLIMIT) != 0) {
        printf("pwhash_str(2) failure\n");
    }
    if (strcmp(str_out, str_out2) == 0) {
        printf("pwhash_str doesn't generate different salts\n");
    }
    if (crypto_pwhash_scryptsalsa208sha256_str_verify(str_out, passwd,
                                                      strlen(passwd)) != 0) {
        printf("pwhash_str_verify failure\n");
    }
    if (crypto_pwhash_scryptsalsa208sha256_str_verify(str_out, passwd,
                                                      strlen(passwd)) != 0) {
        printf("pwhash_str_verify failure\n");
    }
    str_out[14]++;
    if (crypto_pwhash_scryptsalsa208sha256_str_verify(
        str_out, passwd, strlen(passwd)) == 0) {
        printf("pwhash_str_verify(2) failure\n");
    }
    str_out[14]--;

    assert(str_out[crypto_pwhash_scryptsalsa208sha256_STRBYTES - 1U] == 0);
    assert(crypto_pwhash_scryptsalsa208sha256_saltbytes() > 0U);
    assert(crypto_pwhash_scryptsalsa208sha256_strbytes() > 1U);
    assert(crypto_pwhash_scryptsalsa208sha256_strbytes() >
           strlen(crypto_pwhash_scryptsalsa208sha256_strprefix()));
    assert(crypto_pwhash_scryptsalsa208sha256_opslimit_interactive() > 0U);
    assert(crypto_pwhash_scryptsalsa208sha256_memlimit_interactive() > 0U);
    assert(crypto_pwhash_scryptsalsa208sha256_opslimit_sensitive() > 0U);
    assert(crypto_pwhash_scryptsalsa208sha256_memlimit_sensitive() > 0U);

    sodium_free(salt);
    sodium_free(str_out);
    sodium_free(str_out2);

    printf("OK\n");

    return 0;
}