Пример #1
0
// Read Handler, wird asynchron aufgerufen, wenn das OS signalisiert,
// dass Daten von STDIN gelesen werden koennen
void read_handler(const boost::system::error_code &ec, std::size_t bytes_transferred)
{
        if (!ec)
        {
                std::cout.write(bytes.data(), bytes_transferred);
                // weiter asynchron von STDIN lesen
                in.async_read_some(boost::asio::buffer(bytes), read_handler);
        }
}
Пример #2
0
void put_string(entry& e, std::array<char, 64>& sig
	, std::uint64_t& seq
	, std::string const& salt
	, std::array<char, 32> const& pk
	, std::array<char, 64> const& sk
	, char const* str)
{
	using libtorrent::dht::sign_mutable_item;

	e = std::string(str);
	std::vector<char> buf;
	bencode(std::back_inserter(buf), e);
	dht::signature sign;
	++seq;
	sign_mutable_item(buf, salt, dht::sequence_number(seq)
		, dht::public_key(pk.data())
		, dht::secret_key(sk.data()), sign);
	sig = sign.bytes;
}
Пример #3
0
std::chrono::nanoseconds Encryption::DirectEncryptECB(void) {
  rijndael_context rk;
  rijndaelKeySetup(&rk, sc_key.data(), 256);

  auto start = high_resolution_clock::now();
  for (size_t i = 0; i < buffer.size(); i += 16) {
    rijndaelEncrypt(&rk, &buffer[i], &buffer[i]);
  }
  return high_resolution_clock::now() - start;
}
Пример #4
0
ResultCode UpdateConfigNANDSavegame() {
    FileSys::Mode mode = {};
    mode.write_flag = 1;
    mode.create_flag = 1;
    FileSys::Path path("config");
    auto file = cfg_system_save_data->OpenFile(path, mode);
    _assert_msg_(Service_CFG, file != nullptr, "could not open file");
    file->Write(0, CONFIG_SAVEFILE_SIZE, 1, cfg_config_file_buffer.data());
    return RESULT_SUCCESS;
}
Пример #5
0
ResultCode FormatConfig() {
    ResultCode res = DeleteConfigNANDSaveFile();
    if (!res.IsSuccess())
        return res;
    // Delete the old data
    cfg_config_file_buffer.fill(0);
    // Create the header
    SaveFileConfig* config = reinterpret_cast<SaveFileConfig*>(cfg_config_file_buffer.data());
    // This value is hardcoded, taken from 3dbrew, verified by hardware, it's always the same value
    config->data_entries_offset = 0x455C;
    // Insert the default blocks
    res = CreateConfigInfoBlk(0x00050005, sizeof(STEREO_CAMERA_SETTINGS), 0xE,
                              reinterpret_cast<const u8*>(STEREO_CAMERA_SETTINGS.data()));
    if (!res.IsSuccess())
        return res;
    res = CreateConfigInfoBlk(0x00090001, sizeof(CONSOLE_UNIQUE_ID), 0xE,
                              reinterpret_cast<const u8*>(&CONSOLE_UNIQUE_ID));
    if (!res.IsSuccess())
        return res;
    res = CreateConfigInfoBlk(0x000F0004, sizeof(CONSOLE_MODEL), 0x8,
                              reinterpret_cast<const u8*>(&CONSOLE_MODEL));
    if (!res.IsSuccess())
        return res;
    res = CreateConfigInfoBlk(0x000A0002, sizeof(CONSOLE_LANGUAGE), 0xA, &CONSOLE_LANGUAGE);
    if (!res.IsSuccess())
        return res;
    res = CreateConfigInfoBlk(0x00070001, sizeof(SOUND_OUTPUT_MODE), 0xE, &SOUND_OUTPUT_MODE);
    if (!res.IsSuccess())
        return res;
    res = CreateConfigInfoBlk(0x000B0000, sizeof(COUNTRY_INFO), 0xE,
                              reinterpret_cast<const u8*>(&COUNTRY_INFO));
    if (!res.IsSuccess())
        return res;
    res = CreateConfigInfoBlk(0x000A0000, sizeof(CONSOLE_USERNAME_BLOCK), 0xE,
                              reinterpret_cast<const u8*>(&CONSOLE_USERNAME_BLOCK));
    if (!res.IsSuccess())
        return res;
    // Save the buffer to the file
    res = UpdateConfigNANDSavegame();
    if (!res.IsSuccess())
        return res;
    return RESULT_SUCCESS;
}
Пример #6
0
 void
 move(C<I>, const_iterator&& other)
 {
     if(n_ == I)
     {
         new(buf_.data()) iter_t<I>{
             std::move(other.iter<I>())};
         return;
     }
     move(C<I+1>{}, std::move(other));
 }
Пример #7
0
 void
 copy(C<I>, const_iterator const& other)
 {
     if(n_ == I)
     {
         new(buf_.data()) iter_t<I>{
             other.iter<I>()};
         return;
     }
     copy(C<I+1>{}, other);
 }
Пример #8
0
 void
 decrement(C<sizeof...(Bs)>)
 {
     auto constexpr I = sizeof...(Bs);
     if(n_ == I)
     {
         --n_;
         new(buf_.data()) iter_t<I-1>{
             std::get<I-1>(*bs_).end()};
     }
     decrement(C<I-1>{});
 }
Пример #9
0
		virtual Real value(std::array<Real, Dimension + 1> coordinates)
				const {
			assert(interpolant);

			// Pack and call
			NaryMethodConst<Real, Interpolant<Dimension>,
					Dimension, Real> tmp =
					&Interpolant<Dimension>::operator();

			return packAndCall<Dimension>(interpolant, tmp,
					coordinates.data() + 1);
		}
Пример #10
0
static bool WipeFile(const string& Name, int TotalPercent, bool& Cancel, ConsoleTitle* DeleteTitle)
{
	bool Result = false;

	api::SetFileAttributes(Name,FILE_ATTRIBUTE_NORMAL);

	api::FileWalker WipeFile;

	if(WipeFile.Open(Name, FILE_READ_DATA|FILE_WRITE_DATA, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_WRITE_THROUGH|FILE_FLAG_SEQUENTIAL_SCAN))
	{
		const DWORD BufSize=65536;
		if(WipeFile.InitWalk(BufSize))
		{
			static std::array<BYTE, BufSize> Buf;
			static bool BufInit = false;
			if(!BufInit)
			{
				Buf.fill(Global->Opt->WipeSymbol); // используем символ заполнитель
				BufInit = true;
			}

			DWORD StartTime=GetTickCount();
			do
			{
				DWORD Written;
				WipeFile.Write(Buf.data(), WipeFile.GetChunkSize(), Written);
				DWORD CurTime=GetTickCount();
				if (CurTime-StartTime>(DWORD)Global->Opt->RedrawTimeout)
				{
					StartTime=CurTime;

					if (CheckForEscSilent() && ConfirmAbortOp())
					{
						Cancel=true;
						return false;
					}

					ShellDeleteMsg(Name, DEL_WIPEPROCESS, TotalPercent, WipeFile.GetPercent(), DeleteTitle);
				}
			}
			while(WipeFile.Step());

			WipeFile.SetPointer(0,nullptr,FILE_BEGIN);
			WipeFile.SetEnd();
		}
		WipeFile.Close();
		string strTempName;
		FarMkTempEx(strTempName,nullptr,FALSE);
		Result = api::MoveFile(Name,strTempName) && api::DeleteFile(strTempName);
	}
	return Result;
}
Пример #11
0
void sc_synth::run_traced(void)
{
    trace = 0;

#ifndef thread_local
    spin_lock::scoped_lock lock (log_guard);
#endif

    scratchpad_printer printer(trace_scratchpad.data());

    printer.printf("\nTRACE %d  %s    #units: %d\n", id(), this->definition_name(), calc_unit_count);

    for (size_t calc_unit_index = 0; calc_unit_index != calc_unit_count; ++calc_unit_index) {
        Unit * unit = calc_units[calc_unit_index];

        sc_ugen_def * def = reinterpret_cast<sc_ugen_def*>(unit->mUnitDef);
        printer.printf("  unit %zd %s\n    in ", calc_unit_index, def->name());
        for (uint16_t j=0; j!=unit->mNumInputs; ++j) {
            printer.printf(" %g", unit->mInBuf[j][0]);
            if (printer.shouldFlush()) {
#ifdef thread_local
                spin_lock::scoped_lock lock (log_guard);
#endif
                log(printer.data());
                printer.clear();
            }
        }

        printer.printf("\n");

        (unit->mCalcFunc)(unit, unit->mBufLength);

        printer.printf("    out");
        for (int j=0; j<unit->mNumOutputs; ++j) {
            printer.printf(" %g", unit->mOutBuf[j][0]);
            if (printer.shouldFlush()) {
#ifdef thread_local
                spin_lock::scoped_lock lock (log_guard);
#endif
                log(printer.data());
                printer.clear();
            }
        }
        printer.printf("\n");
    }
    printer.printf("\n");

#ifdef thread_local
    spin_lock::scoped_lock lock (log_guard);
#endif
    log(printer.data());
}
Пример #12
0
//private
void StatsReporter::draw()
{
    if (!visible) return;

    nim::SetNextWindowSizeConstraints({ 300.f, 200.f }, { 400.f, 1000.f });
    nim::Begin("Stats:", &visible, ImGuiWindowFlags_ShowBorders);

    static std::array<float, 90> timeValues = { 0.f };
    static std::array<float, 90> frameValues = { 0.f };
    static std::size_t valuesIndex = 0;

    const float elapsed = frameTimer.restart().asSeconds();
    const float frameTime = elapsed * 1000.f;
    const float frameRate = 1.f / elapsed;

    static float avgTime = 0.f;
    avgTime -= avgTime / timeValues.size();
    avgTime += frameTime / timeValues.size();
    std::string avgTStr = "Avg: " + std::to_string(avgTime) + " (ms)";

    static float avgFrame = 0.f;
    avgFrame -= avgFrame / frameValues.size();
    avgFrame += frameRate / frameValues.size();
    std::string avgFStr = "Avg: " + std::to_string(avgFrame);

    timeValues[valuesIndex] = frameTime;
    frameValues[valuesIndex] = frameRate;
    valuesIndex = (valuesIndex + 1) % timeValues.size();
    nim::PlotLines("Frame Time", timeValues.data(), timeValues.size(), valuesIndex, avgTStr.c_str(), 0.f, std::max(33.f, frameTime), ImVec2(0, 40));
    nim::PlotLines("Frame Rate", frameValues.data(), frameValues.size(), valuesIndex, avgFStr.c_str(), 0.f, std::max(950.f, frameRate), ImVec2(0, 40));

    nim::BeginChild("ScrollingRegion", ImVec2(0, -nim::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar);
    nim::TextUnformatted(Stats::getString().c_str(), Stats::getString().c_str() + Stats::getString().size());
    nim::SetScrollHere();
    nim::EndChild();
    nim::End();

    //nim::ShowTestWindow(&visible);
}
Пример #13
0
 void
 construct(C<I>)
 {
     if(std::get<I>(*bs_).begin() !=
         std::get<I>(*bs_).end())
     {
         n_ = I;
         new(buf_.data()) iter_t<I>{
             std::get<I>(*bs_).begin()};
         return;
     }
     construct(C<I+1>{});
 }
Пример #14
0
	static std::vector<uint8_t> encrypt(
		const std::vector<uint8_t> header, 
		const std::vector<uint8_t> plain, 
		const std::vector<uint8_t> footer,
		const std::array<uint8_t, 16>& nonce,
		const std::array<uint8_t, 16>& key) {
		std::vector<uint8_t> cipher;
		cipher.resize(plain.size() + 128);

		unsigned char* c = cipher.data();
		size_t cLen = cipher.size();
		const unsigned char* h = header.empty() ? 0 : header.data();
		size_t hLen = header.size();
		const unsigned char* p = plain.data();
		size_t pLen = plain.size();
		const unsigned char* t = footer.empty() ? 0 : footer.data();
		size_t tLen = footer.size();

		norx_aead_encrypt(c, &cLen, h, hLen, p, pLen, t, tLen, nonce.data(), key.data());
		cipher.resize(cLen);
		return cipher;
	}
Пример #15
0
// ----------------------------------------------------------------------------
ENetPacket* Crypto::encryptSend(BareNetworkString& ns, bool reliable)
{
    // 4 bytes counter and 4 bytes tag
    ENetPacket* p = enet_packet_create(NULL, ns.m_buffer.size() + 8,
        (reliable ? ENET_PACKET_FLAG_RELIABLE :
        (ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT))
        );
    if (p == NULL)
        return NULL;

    std::array<uint8_t, 12> iv = {};
    std::unique_lock<std::mutex> ul(m_crypto_mutex);

    uint32_t val = ++m_packet_counter;
    if (NetworkConfig::get()->isClient())
        memcpy(iv.data(), &val, 4);
    else
        memcpy(iv.data() + 4, &val, 4);

    uint8_t* packet_start = p->data + 8;

    if (EVP_EncryptInit_ex(m_encrypt, NULL, NULL, NULL, iv.data()) != 1)
    {
        enet_packet_destroy(p);
        return NULL;
    }

    int elen;
    if (EVP_EncryptUpdate(m_encrypt, packet_start, &elen, ns.m_buffer.data(),
        (int)ns.m_buffer.size()) != 1)
    {
        enet_packet_destroy(p);
        return NULL;
    }
    if (EVP_EncryptFinal_ex(m_encrypt, unused_16_blocks.data(), &elen) != 1)
    {
        enet_packet_destroy(p);
        return NULL;
    }
    if (EVP_CIPHER_CTX_ctrl(m_encrypt, EVP_CTRL_GCM_GET_TAG, 4, p->data + 4)
        != 1)
    {
        enet_packet_destroy(p);
        return NULL;
    }
    ul.unlock();

    memcpy(p->data, &val, 4);
    return p;
}   // encryptSend
Пример #16
0
std::chrono::nanoseconds Encryption::DirectEncryptCFB(void) {
  rijndael_context rk;
  rijndaelKeySetup(&rk, sc_key.data(), 256);

  auto start = high_resolution_clock::now();

  unsigned char feedback[16] = {};
  for (size_t i = 0; i < buffer.size(); i += 16) {
    rijndaelEncrypt(&rk, feedback, feedback);
    for (size_t j = 0; j < 16; j++)
      feedback[j] ^= buffer[i + j];
  }
  return high_resolution_clock::now() - start;
}
Пример #17
0
void Server::receive() {
    Peer peer;
    boost::system::error_code error;
    auto bytes_transferred =
      socket_.receive_from(boost::asio::buffer(recv_buffer_), peer, 0, error);
    std::cout << "Server received " << bytes_transferred << " bytes"
                 " from " << peer
              << " with " << error.message() << std::endl;
    if (!error) {
      std::cout << "  >> ";
      std::cout.write(recv_buffer_.data(), bytes_transferred);
      std::cout << std::endl;
    }
    receive();
}
Пример #18
0
void pie_TransColouredTriangle(const std::array<Vector3f, 3> &vrt, PIELIGHT c, const glm::mat4 &modelViewMatrix)
{
	pie_SetTexturePage(TEXPAGE_NONE);
	pie_SetRendMode(REND_ADDITIVE);
	glm::vec4 color(c.byte.r / 255.f, c.byte.g / 255.f, c.byte.b / 255.f, 128.f / 255.f);
	const auto &program = pie_ActivateShader(SHADER_GENERIC_COLOR, pie_PerspectiveGet() * modelViewMatrix, color);

	static glBufferWrapper buffer;
	glBindBuffer(GL_ARRAY_BUFFER, buffer.id);
	glBufferData(GL_ARRAY_BUFFER, 3 * sizeof(Vector3f), vrt.data(), GL_STREAM_DRAW);
	glVertexAttribPointer(program.locVertex, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
	glEnableVertexAttribArray(program.locVertex);
	glDrawArrays(GL_TRIANGLE_FAN, 0, 3);
	glDisableVertexAttribArray(program.locVertex);
}
Пример #19
0
void D3DVertexFormat::SetupVertexPointers()
{
	if (!d3d_decl)
	{
		if (FAILED(DX9::D3D::dev->CreateVertexDeclaration(m_elems.data(), &d3d_decl)))
		{
			PanicAlert("Failed to create D3D vertex declaration!");
			return;
		}
	}
	if (d3d_decl)
		DX9::D3D::SetVertexDeclaration(d3d_decl);
	else
		ERROR_LOG(VIDEO, "Invalid D3D decl");
}
Пример #20
0
	void preparePipelines()
	{
		const std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };

		VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCI = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
		VkPipelineRasterizationStateCreateInfo rasterizationStateCI = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0);
		VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
		VkPipelineColorBlendStateCreateInfo colorBlendStateCI = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState);
		VkPipelineDepthStencilStateCreateInfo depthStencilStateCI = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL);
		VkPipelineViewportStateCreateInfo viewportStateCI = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
		VkPipelineMultisampleStateCreateInfo multisampleStateCI = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0);
		VkPipelineDynamicStateCreateInfo dynamicStateCI = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), static_cast<uint32_t>(dynamicStateEnables.size()), 0);

		// Vertex bindings and attributes
		const std::vector<VkVertexInputBindingDescription> vertexInputBindings = {
			vks::initializers::vertexInputBindingDescription(0, sizeof(vkglTF::Model::Vertex), VK_VERTEX_INPUT_RATE_VERTEX),
		};
		const std::vector<VkVertexInputAttributeDescription> vertexInputAttributes = {
			vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0),					// Location 0: Position			
			vks::initializers::vertexInputAttributeDescription(0, 1, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3),	// Location 1: Normal
			vks::initializers::vertexInputAttributeDescription(0, 2, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 6),		// Location 2: UV
		};
		VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo();
		vertexInputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexInputBindings.size());
		vertexInputState.pVertexBindingDescriptions = vertexInputBindings.data();
		vertexInputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexInputAttributes.size());
		vertexInputState.pVertexAttributeDescriptions = vertexInputAttributes.data();

		VkGraphicsPipelineCreateInfo pipelineCreateInfoCI = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass, 0);
		pipelineCreateInfoCI.pVertexInputState = &vertexInputState;
		pipelineCreateInfoCI.pInputAssemblyState = &inputAssemblyStateCI;
		pipelineCreateInfoCI.pRasterizationState = &rasterizationStateCI;
		pipelineCreateInfoCI.pColorBlendState = &colorBlendStateCI;
		pipelineCreateInfoCI.pMultisampleState = &multisampleStateCI;
		pipelineCreateInfoCI.pViewportState = &viewportStateCI;
		pipelineCreateInfoCI.pDepthStencilState = &depthStencilStateCI;
		pipelineCreateInfoCI.pDynamicState = &dynamicStateCI;

		const std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages = {
			loadShader(getAssetPath() + "shaders/conditionalrender/model.vert.spv", VK_SHADER_STAGE_VERTEX_BIT),
			loadShader(getAssetPath() + "shaders/conditionalrender/model.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)
		};

		pipelineCreateInfoCI.stageCount = static_cast<uint32_t>(shaderStages.size());
		pipelineCreateInfoCI.pStages = shaderStages.data();

		VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfoCI, nullptr, &pipeline));
	}
Пример #21
0
TEST(ec, SignAndVerify)
{
  static constexpr std::array<u8, 20> HASH = {{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9,
                                               0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}};

  auto signature = Common::ec::Sign(PRIVATE_KEY.data(), HASH.data());
  EXPECT_TRUE(Common::ec::VerifySignature(PUBLIC_KEY.data(), signature.data(), HASH.data()));
  signature.fill(0xff);
  EXPECT_FALSE(Common::ec::VerifySignature(PUBLIC_KEY.data(), signature.data(), HASH.data()));
}
Пример #22
0
    bool ConeShape2D::load(const float width, const float height)
    {
        auto temp = std::make_unique<b2PolygonShape>();

        const std::array<glm::vec2, 3> points =
        {
            glm::vec2(0.f, height*0.5f),
            glm::vec2(-width * 0.5f, -height*0.5f),
            glm::vec2(width * 0.5f, -height*0.5f)
        };

        temp->Set(reinterpret_cast<const b2Vec2*>(points.data()), points.size());
        m_shape = std::move(temp);

        return true;
    }
Пример #23
0
    void insertDataFrame(std::int32_t activeTermId, std::int32_t offset)
    {
        int termBufferIndex = LogBufferDescriptor::indexByTerm(INITIAL_TERM_ID, activeTermId);
        AtomicBuffer& buffer = m_termBuffers[termBufferIndex];
        DataFrameHeader::DataFrameHeaderDefn& frame = buffer.overlayStruct<DataFrameHeader::DataFrameHeaderDefn>(offset);
        const index_t msgLength = static_cast<index_t>(DATA.size());

        frame.frameLength = DataFrameHeader::LENGTH + msgLength;
        frame.version = DataFrameHeader::CURRENT_VERSION;
        frame.flags = FrameDescriptor::UNFRAGMENTED;
        frame.type = DataFrameHeader::HDR_TYPE_DATA;
        frame.termOffset = offset;
        frame.sessionId = SESSION_ID;
        frame.streamId = STREAM_ID;
        frame.termId = activeTermId;
        buffer.putBytes(offset + DataFrameHeader::LENGTH, DATA.data(), msgLength);
    }
Пример #24
0
void put_string(entry& e, std::array<char, 64>& sig, boost::uint64_t& seq
	, std::string const& salt, char const* public_key, char const* private_key
	, char const* str)
{
	using libtorrent::dht::sign_mutable_item;

	e = std::string(str);
	std::vector<char> buf;
	bencode(std::back_inserter(buf), e);
	++seq;
	sign_mutable_item(std::pair<char const*, int>(&buf[0], int(buf.size()))
		, std::pair<char const*, int>(&salt[0], int(salt.size()))
		, seq
		, public_key
		, private_key
		, sig.data());
}
Пример #25
0
//-----------------------------------------------------------------------
void GraphicsContextDirect3D11::SetSampler(int index, NativeSamplerState* samplerIn)
{
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(index < D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT);
    POMDOG_ASSERT(samplerIn != nullptr);

    auto sampler = static_cast<SamplerStateDirect3D11*>(samplerIn);

    POMDOG_ASSERT(sampler != nullptr);
    POMDOG_ASSERT(sampler == dynamic_cast<SamplerStateDirect3D11*>(samplerIn));
    POMDOG_ASSERT(sampler->GetSamplerState() != nullptr);

    std::array<ID3D11SamplerState*, 1> const states = {
        sampler->GetSamplerState() };

    POMDOG_ASSERT(deviceContext);
    deviceContext->PSSetSamplers(index, states.size(), states.data());
}
Пример #26
0
 void
 decrement(C<I>)
 {
     if(n_ == I)
     {
         if(iter<I>() != std::get<I>(*bs_).begin())
         {
             --iter<I>();
             return;
         }
         --n_;
         using Iter = iter_t<I>;
         iter<I>().~Iter();
         new(buf_.data()) iter_t<I-1>{
             std::get<I-1>(*bs_).end()};
     }
     decrement(C<I-1>{});
 }
Пример #27
0
void c_tun_device_windows::set_ipv6_address
	(const std::array<uint8_t, 16> &binary_address, int prefixLen)
{
	_fact("Setting IPv6 address, prefixLen="<<prefixLen);
	std::wstring human_name = get_human_name(m_guid);
	NET_LUID luid = get_luid(human_name);
	_fact("Setting address on human_name " << to_string(human_name));// << " luid=" << to_string(luid));
	// remove old address
	MIB_UNICASTIPADDRESS_TABLE *table = nullptr;
	NETIOAPI_API status = GetUnicastIpAddressTable(AF_INET6, &table);
	if (status != NO_ERROR) throw std::runtime_error("GetUnicastIpAddressTable error, code");
	for (int i = 0; i < static_cast<int>(table->NumEntries); ++i) {
		_info("Removing old addresses, i="<<i);
		if (table->Table[i].InterfaceLuid.Value == luid.Value) {
		_info("Removing old addresses, entry i="<<i<<" - will remove");
			if (DeleteUnicastIpAddressEntry(&table->Table[i]) != NO_ERROR) {
				FreeMibTable(table);
				throw std::runtime_error("DeleteUnicastIpAddressEntry error");
			}
		}
	}
	FreeMibTable(table);

	// set new address
	_fact("Setting new IP address");
	MIB_UNICASTIPADDRESS_ROW iprow;
	std::memset(&iprow, 0, sizeof(iprow));
	iprow.PrefixOrigin = IpPrefixOriginUnchanged;
	iprow.SuffixOrigin = IpSuffixOriginUnchanged;
	iprow.ValidLifetime = 0xFFFFFFFF;
	iprow.PreferredLifetime = 0xFFFFFFFF;
	iprow.OnLinkPrefixLength = 0xFF;

	iprow.InterfaceLuid = luid;
	iprow.Address.si_family = AF_INET6;
	std::memcpy(&iprow.Address.Ipv6.sin6_addr, binary_address.data(), binary_address.size());
	iprow.OnLinkPrefixLength = prefixLen;

	_fact("Creating unicast IP");
	status = CreateUnicastIpAddressEntry(&iprow);
	if (status != NO_ERROR) throw std::runtime_error("CreateUnicastIpAddressEntry error");
	_goal("Created unicast IP, status=" << status);
}
Пример #28
0
// ============================================================================
bool Crypto::encryptConnectionRequest(BareNetworkString& ns)
{
    std::vector<uint8_t> cipher(ns.m_buffer.size() + 4, 0);

    int elen;
    if (EVP_EncryptInit_ex(m_encrypt, NULL, NULL, NULL, NULL) != 1)
        return false;
    if (EVP_EncryptUpdate(m_encrypt, cipher.data() + 4, &elen,
        ns.m_buffer.data(), (int)ns.m_buffer.size()) != 1)
        return false;
    if (EVP_EncryptFinal_ex(m_encrypt, unused_16_blocks.data(), &elen) != 1)
        return false;
    if (EVP_CIPHER_CTX_ctrl(m_encrypt, EVP_CTRL_GCM_GET_TAG, 4, cipher.data())
        != 1)
        return false;

    std::swap(ns.m_buffer, cipher);
    return true;
}   // encryptConnectionRequest
Пример #29
0
void AppState::updateKeyInputState() {
    DIDEVICEOBJECTDATA didod[kKeyInputBufferSize]; // Receives buffered data
    KeyInputData data_buff[kKeyInputBufferSize];
    DWORD dwElements = kKeyInputBufferSize;

    dx::throwIfFailed(
        keyboard_device_->GetDeviceState(sizeof(key_input_diks_), key_input_diks_.data())
    );

    HRESULT hr = keyboard_device_->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), didod, &dwElements, 0);
    if (hr == DI_OK) {
        ASSERT(dwElements != 0);
        std::transform(didod, didod + dwElements, data_buff, [this](DIDEVICEOBJECTDATA& d) {
            return KeyInputData {getKeyCode(d.dwOfs) , d.dwData & 0x80};
        });
        KeyboardInput::instance().updateState( { data_buff, data_buff + dwElements });
    } else {
        LOGI(kLogSignWin,"GetDeviceData[%ld]", hr);
    }
}
Пример #30
0
 void onMessageReceived(const error_code& ec, size_t nrBytes)
 {
     auto onMessageReceivedWrapper = [this](const error_code& ec,
                                            size_t nrBytes)
     {
         this->onMessageReceived(ec, nrBytes);
     };
     cout << "Received " << data_.data() << "\n";
     try
     {
     socket_.read_some(boost::asio::buffer(data_));
     socket_.async_read_some(boost::asio::buffer(data_),
                             onMessageReceivedWrapper);
     data_.fill(0);
     }
     catch(std::exception& e)
     {
         cout << e.what() << "\n";
     }
 }