Пример #1
0
//==============================================================================
// ポリゴンの初期化
//==============================================================================
void InitPolygon( void )
{
	// デバイスの取得
	LPDIRECT3DDEVICE9 g_pD3DDevice = GetDevice();

	// テクスチャファイルの読み込み
	if ( FAILED( D3DXCreateTextureFromFile( g_pD3DDevice, POLYGON_TEXTURENAME1, &g_pTexturePolygon[ 0 ]/* テクスチャサーフェスに入る */ ) ) )
	{
		MessageBox( NULL, "ERROR!!", "ERROR!!", NULL );
	}
	if ( FAILED( D3DXCreateTextureFromFile( g_pD3DDevice, POLYGON_TEXTURENAME2, &g_pTexturePolygon[ 1 ]/* テクスチャサーフェスに入る */ ) ) )
	{
		MessageBox( NULL, "ERROR!!", "ERROR!!", NULL );
	}

	// 頂点座標の作成
	MakeVertexPolygon(g_pD3DDevice);

	// 頂点フォーマットの設定
	g_pD3DDevice->SetFVF( FVF_VERTEX_2D );
}
Пример #2
0
//=============================================================================
// 描画処理
//=============================================================================
void DrawPlaybar(void)
{
	LPDIRECT3DDEVICE9 pDevice = GetDevice();

	// 頂点バッファをデバイスのデータストリームにバインド
	pDevice->SetStreamSource(0, g_pD3DVtxBuffPlaybar, 0, sizeof(VERTEX_2D));

	// 頂点フォーマットの設定
	pDevice->SetFVF(FVF_VERTEX_2D);

	for(int nCntPlayBar = 0; nCntPlayBar < MAX_PLAYBAR; nCntPlayBar++)
	{
		if(g_aPlaybar[nCntPlayBar].bUse == true)
		{
			// テクスチャの設定
			pDevice->SetTexture(0, g_apD3DTexturePlaybar[g_aPlaybar[nCntPlayBar].nType]);

			// ポリゴンの描画
			pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, (nCntPlayBar * 4), NUM_POLYGON);
		}
	}
}
Пример #3
0
//=============================================================================
// 描画処理
//=============================================================================
void DrawBotton(void)
{
	LPDIRECT3DDEVICE9 pDevice = GetDevice();

	// 頂点バッファをデバイスのデータストリームにバインド
	pDevice->SetStreamSource(0, g_pD3DVtxBuffBotton, 0, sizeof(VERTEX_2D));

	// 頂点フォーマットの設定
	pDevice->SetFVF(FVF_VERTEX_2D);

	for(int nCntBot = 0; nCntBot < MAX_BOTTON; nCntBot++)
	{
		if(g_aBotton[nCntBot].bUse == true)
		{
			// テクスチャの設定
			pDevice->SetTexture(0, g_apD3DTextureBotton[g_aBotton[nCntBot].nType]);

			// ポリゴンの描画
			pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, (nCntBot * 4), NUM_POLYGON);
		}
	}
}
Пример #4
0
/*
 * This is called when the application wants a temperature sensor to be restored to the default
 * factory settings. This action is executed using the Temperature Sensor Insect Configuration
 * PGN (65287L).
 */
void tTempSensorProxy::ResetToFactorySettings()
{
    tNDP2kDevice* pDevice;

    if( GetDevice( &pDevice ) == true )
    {
        /* Structure holding the Temp Sensor Configuration Pgn data for encoding */
        SystemData::tcPgn65287LowranceData  configData;

        /* Fill the configuration data to set the new type */
        configData.manufactureId = 140;
        configData.industryGroup = 4;
        configData.confFuncTempInsect = (unsigned char)TempConfigFunction_ResetDefault;
        configData.deviceAddress = pDevice->Address();
        configData.tempSensorInstance = 0xFF;
        configData.tempCalibration = 0xFF;
        configData.setSystemInstance = 0xFF;

        /* Ask the Stack to send the message */
        m_NDP2k.Send(65287, ISSF_PGN65287_LOWRANCE, &configData, SystemData::cEncodePgn65287Lowrance);
    }
}
Пример #5
0
void BufferD3D11Impl::CreateViewInternal( const BufferViewDesc &OrigViewDesc, IBufferView **ppView, bool bIsDefaultView )
{
    VERIFY( ppView != nullptr, "Null pointer provided" );
    if( !ppView )return;
    VERIFY( *ppView == nullptr, "Overwriting reference to existing object may cause memory leaks" );

    *ppView = nullptr;

    try
    {
        auto *pDeviceD3D11Impl = ValidatedCast<RenderDeviceD3D11Impl>(GetDevice());
        auto &BuffViewAllocator = pDeviceD3D11Impl->GetBuffViewObjAllocator();
        VERIFY( &BuffViewAllocator == &m_dbgBuffViewAllocator, "Buff view allocator does not match allocator provided at buffer initialization" );

        BufferViewDesc ViewDesc = OrigViewDesc;
        if( ViewDesc.ViewType == BUFFER_VIEW_UNORDERED_ACCESS )
        {
            CComPtr<ID3D11UnorderedAccessView> pUAV;
            CreateUAV( ViewDesc, &pUAV );
            *ppView = NEW_RC_OBJ(BuffViewAllocator, "BufferViewD3D11Impl instance",  BufferViewD3D11Impl, bIsDefaultView ? this : nullptr)
                                ( pDeviceD3D11Impl, ViewDesc, this, pUAV, bIsDefaultView );
        }
        else if( ViewDesc.ViewType == BUFFER_VIEW_SHADER_RESOURCE )
        {
			CComPtr<ID3D11ShaderResourceView> pSRV;
            CreateSRV( ViewDesc, &pSRV );
            *ppView = NEW_RC_OBJ(BuffViewAllocator, "BufferViewD3D11Impl instance",  BufferViewD3D11Impl, bIsDefaultView ? this : nullptr)
                                (pDeviceD3D11Impl, ViewDesc, this, pSRV, bIsDefaultView );
        }

        if( !bIsDefaultView && *ppView )
            (*ppView)->AddRef();
    }
    catch( const std::runtime_error & )
    {
        const auto *ViewTypeName = GetBufferViewTypeLiteralName(OrigViewDesc.ViewType);
        LOG_ERROR("Failed to create view \"", OrigViewDesc.Name ? OrigViewDesc.Name : "", "\" (", ViewTypeName, ") for buffer \"", m_Desc.Name, "\"" );
    }
}
  Tools::AutoDeleter<VkShaderModule, PFN_vkDestroyShaderModule> Tutorial03::CreateShaderModule( const char* filename ) {
    const std::vector<char> code = Tools::GetBinaryFileContents( filename );
    if( code.size() == 0 ) {
      return Tools::AutoDeleter<VkShaderModule, PFN_vkDestroyShaderModule>();
    }

    VkShaderModuleCreateInfo shader_module_create_info = {
      VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,    // VkStructureType                sType
      nullptr,                                        // const void                    *pNext
      0,                                              // VkShaderModuleCreateFlags      flags
      code.size(),                                    // size_t                         codeSize
      reinterpret_cast<const uint32_t*>(&code[0])     // const uint32_t                *pCode
    };

    VkShaderModule shader_module;
    if( vkCreateShaderModule( GetDevice(), &shader_module_create_info, nullptr, &shader_module ) != VK_SUCCESS ) {
      std::cout << "Could not create shader module from a \"" << filename << "\" file!" << std::endl;
      return Tools::AutoDeleter<VkShaderModule, PFN_vkDestroyShaderModule>();
    }

    return Tools::AutoDeleter<VkShaderModule, PFN_vkDestroyShaderModule>( shader_module, vkDestroyShaderModule, GetDevice() );
  }
Пример #7
0
/******************************************************************************
* 関数名:DrawPause
* 
* 引数  :
* 戻り値:
* 説明  :
******************************************************************************/
void DrawPause( void )
{
	LPDIRECT3DDEVICE9 pDevice = GetDevice();

	for( int cnt = 0 ; cnt < PAUSE_TEX_MAX ; cnt++ )
	{
		if( g_bPause == true )
		{
			//頂点バッファをデータストリームにバインド
			pDevice -> SetStreamSource( 0 , g_pause[cnt].pVtxBuffPause , 0 , sizeof( VERTEX_2D ));

			//頂点フォーマット
			pDevice -> SetFVF( FVF_VERTEX_2D );

			pDevice -> SetTexture( 0 , g_pTexturePause[cnt] );

			//ポリゴンの描画
			pDevice -> DrawPrimitive( D3DPT_TRIANGLESTRIP , 0 , 2 );
		}
	}

}
Пример #8
0
bool CD3DWOWM2ItemModel::BuildModel()
{
	D3DLOCK_FOR_OBJECT_MODIFY

	CBLZWOWDatabase::BLZ_DB_ITEM_DISPLAY_INFO * pDisplayInfo=CBLZWOWDatabase::GetInstance()->GetItemDisplayInfo(m_ItemDisplayID);
	if(pDisplayInfo)
	{
		CEasyString TexturePath=GetPathDirectory(m_pModelResource->GetName());
		if(m_ItemHandType==IHT_LEFT)
			TexturePath+=pDisplayInfo->LeftModelTexture+".blp";
		else
			TexturePath+=pDisplayInfo->RightModelTexture+".blp";
		CD3DTexture * pTexture=GetDevice()->GetTextureManager()->LoadTexture(TexturePath);
		if(pTexture)
		{
			for(int j=0;j<GetSubMeshCount();j++)
			{
				CD3DSubMesh  * pSubMesh=GetSubMesh(j);
				if(pSubMesh)
				{
					for(UINT i=0;i<pSubMesh->GetMaterial().GetTextureLayerCount();i++)
					{
						UINT TextureType=(pSubMesh->GetMaterial().GetTextureProperty(i)&CD3DWOWM2ModelResource::TF_SKIN_TEXTURE_TYPE_MASK)>>
							CD3DWOWM2ModelResource::TF_SKIN_TEXTURE_TYPE_SHIFT;
						if(TextureType!=D3D_TEXTURE_TYPE_DIRECT)
						{
							pSubMesh->GetMaterial().SetTexture(i,pTexture);
							pTexture->AddUseRef();
						}
					}

				}
			}
			SAFE_RELEASE(pTexture);			
		}
	}
	
	return true;
}
Пример #9
0
bool C1WireByOWFS::FindDevice(const std::string inDir, const std::string sID, /*out*/_t1WireDevice& device) const
{
    bool found = false;
    DIR *d=opendir(inDir.c_str());
    if (d != NULL)
    {
        struct dirent *de=NULL;
        // Loop while not NULL or not found
        while((de=readdir(d)) && !found)
        {
            // Check dir
            if (!IsValidDir(de))
                continue;

            // Get the device from it's dirname
            GetDevice(inDir, de->d_name, device);

            // Check if it's the device we are looking for
            if (device.devid.compare(0,sID.length(),sID)==0)
            {
                found=true;
                continue;
            }

            // Else, try to scan hubs (recursively)
            if (device.family==microlan_coupler)
            {
                // Search in "main" and "aux" dir
                found=FindDevice(inDir + "/" + de->d_name + HUB_MAIN_SUB_PATH, sID, device);
                if(!found)
                    found=FindDevice(inDir + "/" + de->d_name + HUB_AUX_SUB_PATH, sID, device);
            }
        }
    }

    closedir(d);
    return found;
}
Пример #10
0
void cConnectionIGMP::Welcome()
{
	cDevice *device = NULL;
	if (ProvidesChannel(m_Channel, 0))
		device = GetDevice(m_Channel, 0);
	if (device != NULL) {
		device->SwitchChannel(m_Channel, false);
		m_LiveStreamer = new cStreamdevLiveStreamer(0, this);
		if (m_LiveStreamer->SetChannel(m_Channel, m_StreamType)) {
			m_LiveStreamer->SetDevice(device);
			if (!SetDSCP())
				LOG_ERROR_STR("unable to set DSCP sockopt");
			Dprintf("streamer start\n");
			m_LiveStreamer->Start(this);
		}
		else {
			esyslog("streamdev-server IGMP: SetChannel failed");
			DELETENULL(m_LiveStreamer);
		}
	}
	else
		esyslog("streamdev-server IGMP: GetDevice failed");
}
void BufferD3D12Impl::CreateViewInternal( const BufferViewDesc &OrigViewDesc, IBufferView **ppView, bool bIsDefaultView )
{
    VERIFY( ppView != nullptr, "Null pointer provided" );
    if( !ppView )return;
    VERIFY( *ppView == nullptr, "Overwriting reference to existing object may cause memory leaks" );

    *ppView = nullptr;

    try
    {
        auto *pDeviceD3D12Impl = ValidatedCast<RenderDeviceD3D12Impl>(GetDevice());
        auto &BuffViewAllocator = pDeviceD3D12Impl->GetBuffViewObjAllocator();
        VERIFY( &BuffViewAllocator == &m_dbgBuffViewAllocator, "Buff view allocator does not match allocator provided at buffer initialization" );

        BufferViewDesc ViewDesc = OrigViewDesc;
        if( ViewDesc.ViewType == BUFFER_VIEW_UNORDERED_ACCESS )
        {
            auto UAVHandleAlloc = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
            CreateUAV( ViewDesc, UAVHandleAlloc.GetCpuHandle() );
            *ppView = NEW(BuffViewAllocator, "BufferViewD3D12Impl instance", BufferViewD3D12Impl, GetDevice(), ViewDesc, this, std::move(UAVHandleAlloc), bIsDefaultView );
        }
        else if( ViewDesc.ViewType == BUFFER_VIEW_SHADER_RESOURCE )
        {
			auto SRVHandleAlloc = pDeviceD3D12Impl->AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
            CreateSRV( ViewDesc, SRVHandleAlloc.GetCpuHandle() );
            *ppView = NEW(BuffViewAllocator, "BufferViewD3D12Impl instance", BufferViewD3D12Impl, GetDevice(), ViewDesc, this, std::move(SRVHandleAlloc), bIsDefaultView );
        }

        if( !bIsDefaultView && *ppView )
            (*ppView)->AddRef();
    }
    catch( const std::runtime_error & )
    {
        const auto *ViewTypeName = GetBufferViewTypeLiteralName(OrigViewDesc.ViewType);
        LOG_ERROR("Failed to create view \"", OrigViewDesc.Name ? OrigViewDesc.Name : "", "\" (", ViewTypeName, ") for buffer \"", m_Desc.Name, "\"" )
    }
}
Пример #12
0
/*******************************************************************************
* DrawGameStart
*******************************************************************************/
void DrawTitleGameStart(void)
{

	LPDIRECT3DDEVICE9 pDevice = GetDevice();
	LPDIRECT3DTEXTURE9 *pTitleTex = GetTitleTexture();

	//頂点バッファをデバイスのデータストリームにバインド
	pDevice->SetStreamSource(0, g_pVtxBufferTitleGameStart, 0, sizeof(VERTEX_2D));

	//頂点フォーマットの設定
	pDevice->SetFVF(FVF_VERTEX_2D);

	//テクスチャの設定
	pDevice->SetTexture(0, pTitleTex[TITLE_START]);

	//ポリゴンの描画
	pDevice->DrawPrimitive(
		D3DPT_TRIANGLESTRIP,	//プリミティブの種類
		0,						//ロードする最初の頂点インデックス
		NUM_POLYGON				//ポリゴンの数
	);


}
Пример #13
0
void
VRManager::RefreshVRDevices()
{
  nsTArray<RefPtr<gfx::VRHMDInfo> > devices;

  for (uint32_t i = 0; i < mManagers.Length(); ++i) {
    mManagers[i]->GetHMDs(devices);
  }

  bool deviceInfoChanged = false;

  if (devices.Length() != mVRDevices.Count()) {
    deviceInfoChanged = true;
  }

  for (const auto& device: devices) {
    RefPtr<VRHMDInfo> oldDevice = GetDevice(device->GetDeviceInfo().GetDeviceID());
    if (oldDevice == nullptr) {
      deviceInfoChanged = true;
      break;
    }
    if (oldDevice->GetDeviceInfo() != device->GetDeviceInfo()) {
      deviceInfoChanged = true;
      break;
    }
  }

  if (deviceInfoChanged) {
    mVRDevices.Clear();
    for (const auto& device: devices) {
      mVRDevices.Put(device->GetDeviceInfo().GetDeviceID(), device);
    }
  }

  DispatchVRDeviceInfoUpdate();
}
Пример #14
0
//==============================================================================
// 終了処理
//==============================================================================
void UninitPolygon( void )
{
	LPDIRECT3DDEVICE9 g_pD3DDevice = GetDevice();

	// マクロセーフリリースで作れば便利

	// デバイスを解放
	if ( g_pD3DDevice != NULL )
	{
		g_pD3DDevice->Release();	// Direct3DDeviceのメモリエリア解放
		g_pD3DDevice = NULL;
	}
	// テクスチャを解放
	if ( g_pTexturePolygon[ 0 ] != NULL )
	{
		g_pTexturePolygon[ 0 ]->Release();
		g_pTexturePolygon[ 0 ] = NULL;
	}
	if ( g_pTexturePolygon[ 1 ] != NULL )
	{
		g_pTexturePolygon[ 1 ]->Release();
		g_pTexturePolygon[ 1 ] = NULL;
	}
}
Пример #15
0
LPD3DXFONT CFontManager::AddFont(const char * name, UINT size, UINT weight, bool italic)
{
	for (UINT i = 0; i < m_fonts.size(); i ++)
	{
		if (strcmp(name, m_fonts[i]->name) == 0 
			&& size == m_fonts[i]->size 
			&& weight == m_fonts[i]->weight 
			&& italic == m_fonts[i]->italic)
			return m_fonts[i]->font;
	}

	FontItem * f = new FontItem;
	strcpy(f->name, name);
	f->size = size;
	f->italic = italic;
	f->weight = weight;
	D3DXCreateFont(GetDevice(), size, 0, weight, 1, italic, 
					DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, 
					DEFAULT_PITCH | FF_DONTCARE, name, & f->font);

	m_fonts.push_back(f);

	return f->font;
}
  bool Tutorial03::CreateFramebuffers() {
    const std::vector<ImageParameters> &swap_chain_images = GetSwapChain().Images;
    Vulkan.Framebuffers.resize( swap_chain_images.size() );

    for( size_t i = 0; i < swap_chain_images.size(); ++i ) {
      VkFramebufferCreateInfo framebuffer_create_info = {
        VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,  // VkStructureType                sType
        nullptr,                                    // const void                    *pNext
        0,                                          // VkFramebufferCreateFlags       flags
        Vulkan.RenderPass,                          // VkRenderPass                   renderPass
        1,                                          // uint32_t                       attachmentCount
        &swap_chain_images[i].ImageView,            // const VkImageView             *pAttachments
        300,                                        // uint32_t                       width
        300,                                        // uint32_t                       height
        1                                           // uint32_t                       layers
      };

      if( vkCreateFramebuffer( GetDevice(), &framebuffer_create_info, nullptr, &Vulkan.Framebuffers[i] ) != VK_SUCCESS ) {
        std::cout << "Could not create a framebuffer!" << std::endl;
        return false;
      }
    }
    return true;
  }
void BufferD3D12Impl :: Map(IDeviceContext *pContext, MAP_TYPE MapType, Uint32 MapFlags, PVoid &pMappedData)
{
    TBufferBase::Map( pContext, MapType, MapFlags, pMappedData );
    auto *pDeviceContextD3D12 = ValidatedCast<DeviceContextD3D12Impl>(pContext);
#ifdef _DEBUG
    m_DbgMapType[pDeviceContextD3D12->GetContextId()] = MapType;
#endif
    if (MapType == MAP_READ )
    {
        LOG_WARNING_MESSAGE_ONCE("Mapping CPU buffer for reading on D3D12 currently requires flushing context and idling GPU");
        pDeviceContextD3D12->Flush();
        auto *pDeviceD3D12 = ValidatedCast<RenderDeviceD3D12Impl>(GetDevice());
        pDeviceD3D12->IdleGPU();

        VERIFY(m_Desc.Usage == USAGE_CPU_ACCESSIBLE, "Buffer must be created as USAGE_CPU_ACCESSIBLE to be mapped for reading")
        D3D12_RANGE MapRange;
        MapRange.Begin = 0;
        MapRange.End = m_Desc.uiSizeInBytes;
        m_pd3d12Resource->Map(0, &MapRange, &pMappedData);
    }
    else if(MapType == MAP_WRITE_DISCARD)
    {
        auto *pCtxD3D12 = ValidatedCast<DeviceContextD3D12Impl>(pContext);
        auto ContextId = pDeviceContextD3D12->GetContextId();
        m_DynamicData[ContextId] = pCtxD3D12->AllocateDynamicSpace(m_Desc.uiSizeInBytes);
        pMappedData = m_DynamicData[ContextId].CPUAddress;
    }
    else if(MapType == MAP_READ_WRITE || MapType == MAP_WRITE)
    {
        LOG_ERROR("D3D12 allows writing to CPU-readable buffer, but it is not accessable by GPU")
    }
    else
    {
        LOG_ERROR("Only MAP_WRITE_DISCARD and MAP_READ are currently implemented in D3D12")
    }
}
Пример #18
0
TEST_F(ContextTest, FromDeviceList) {
  cl::Device Dev = GetDevice();
  cl_context_properties *DefaultProps = GetProps();

  cl::Context Ctx(std::vector<cl::Device>(1, Dev), DefaultProps);

  std::vector<cl::Device> Devs = Ctx.getInfo<CL_CONTEXT_DEVICES>();

  std::vector<cl_context_properties> Props;
  Props = Ctx.getInfo<CL_CONTEXT_PROPERTIES>();

  EXPECT_EQ(1u, Ctx.getInfo<CL_CONTEXT_NUM_DEVICES>());
  EXPECT_EQ(1u, Devs.size());

  // Note: the following check make sense only into OpenCRun.
  EXPECT_EQ(Dev(), Devs[0]());

  EXPECT_EQ(3u, Props.size());

  // Unroll the checking loop by hand, to provide better error reporting.
  EXPECT_EQ(DefaultProps[0], Props[0]);
  EXPECT_EQ(DefaultProps[1], Props[1]);
  EXPECT_EQ(DefaultProps[2], Props[2]);
}
Пример #19
0
// Effects creating
bool EnsureShaders1()
{
    // Get or create device
    LPDIRECT3DDEVICE9 device = GetDevice();
    if (device == NULL) return false;

    LPD3DXBUFFER errorsBuffer = NULL;

    // Load Phong effect
    if (phongShader == NULL)
    {
        D3DXCreateEffectFromFile(device, L"NuGenBioChem.Native.Phong.fx", NULL, NULL, D3DXSHADER_OPTIMIZATION_LEVEL3, NULL, &phongShader, &errorsBuffer);

        if (phongShader == NULL)
        {
            if (errorsBuffer != NULL)
            {
                // TIP: hit breakpoint here to see errors
                char* errors = (char*)errorsBuffer->GetBufferPointer();
                errorsBuffer->Release();
            }
            return false;
        }

        phongShader->SetTechnique("Phong");
    }

    // Load Quasi-realistic molecule shading model
    if (quasiShader == NULL)
    {
        // TODO: Add quasi-realistic molecule shading effect
    }

    if (errorsBuffer != NULL) errorsBuffer->Release();
    return true;
}
Пример #20
0
void BillboardObject::Appear(){

	D3DXMATRIXA16 matWorld = BillboardMatrixSetting();

	GetDevice()->SetVertexShader(NULL);

	GetDevice()->SetStreamSource( 0, pMyVB, 0, sizeof(MY_VERTEX) );

	GetDevice()->SetFVF(MY_VERTEX_FVF);

	GetDevice()->SetTexture(0,pTex);
	GetDevice()->SetTransform(D3DTS_WORLD,&matWorld);


	// •`‰æ
	GetDevice()->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 );


}
Пример #21
0
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
bool Renderer::BeginRecord( int32_t width, int32_t height )
{
	assert( !m_recording );
	assert( m_recordingTempTarget == NULL );
	assert( m_recordingTempDepth == NULL );

	m_recordingWidth = width;
	m_recordingHeight = height;

	HRESULT hr;

	hr = GetDevice()->CreateTexture( width, height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_recordingTargetTexture, NULL );
	if( FAILED( hr ) ) return false;

	m_recordingTargetTexture->GetSurfaceLevel( 0, &m_recordingTarget );

	GetDevice()->CreateDepthStencilSurface( width, height, D3DFMT_D16, D3DMULTISAMPLE_NONE, 0, TRUE, &m_recordingDepth, NULL );

	if( m_recordingTarget == NULL || m_recordingDepth == NULL )
	{
		ES_SAFE_RELEASE( m_recordingTarget );
		ES_SAFE_RELEASE( m_recordingTargetTexture );
		ES_SAFE_RELEASE( m_recordingDepth );
		return false;
	}

	GetDevice()->GetRenderTarget( 0, &m_recordingTempTarget );
	GetDevice()->GetDepthStencilSurface( &m_recordingTempDepth );

	GetDevice()->SetRenderTarget( 0, m_recordingTarget );
	GetDevice()->SetDepthStencilSurface( m_recordingDepth );
	
	m_recording = true;

	return true;
}
Пример #22
0
void CEXIChannel::RegisterMMIO(MMIO::Mapping* mmio, u32 base)
{
  // Warning: the base is not aligned on a page boundary here. We can't use |
  // to select a register address, instead we need to use +.

  mmio->Register(base + EXI_STATUS, MMIO::ComplexRead<u32>([this](u32) {
                   // check if external device is present
                   // pretty sure it is memcard only, not entirely sure
                   if (m_ChannelId == 2)
                   {
                     m_Status.EXT = 0;
                   }
                   else
                   {
                     m_Status.EXT = GetDevice(1)->IsPresent() ? 1 : 0;
                   }

                   return m_Status.Hex;
                 }),
                 MMIO::ComplexWrite<u32>([this](u32, u32 val) {
                   UEXI_STATUS newStatus(val);

                   m_Status.EXIINTMASK = newStatus.EXIINTMASK;
                   if (newStatus.EXIINT)
                     m_Status.EXIINT = 0;

                   m_Status.TCINTMASK = newStatus.TCINTMASK;
                   if (newStatus.TCINT)
                     m_Status.TCINT = 0;

                   m_Status.CLK = newStatus.CLK;

                   if (m_ChannelId == 0 || m_ChannelId == 1)
                   {
                     m_Status.EXTINTMASK = newStatus.EXTINTMASK;

                     if (newStatus.EXTINT)
                       m_Status.EXTINT = 0;
                   }

                   if (m_ChannelId == 0)
                     m_Status.ROMDIS = newStatus.ROMDIS;

                   IEXIDevice* pDevice = GetDevice(m_Status.CHIP_SELECT ^ newStatus.CHIP_SELECT);
                   m_Status.CHIP_SELECT = newStatus.CHIP_SELECT;
                   if (pDevice != nullptr)
                     pDevice->SetCS(m_Status.CHIP_SELECT);

                   ExpansionInterface::UpdateInterrupts();
                 }));

  mmio->Register(base + EXI_DMAADDR, MMIO::DirectRead<u32>(&m_DMAMemoryAddress),
                 MMIO::DirectWrite<u32>(&m_DMAMemoryAddress));
  mmio->Register(base + EXI_DMALENGTH, MMIO::DirectRead<u32>(&m_DMALength),
                 MMIO::DirectWrite<u32>(&m_DMALength));
  mmio->Register(base + EXI_DMACONTROL, MMIO::DirectRead<u32>(&m_Control.Hex),
                 MMIO::ComplexWrite<u32>([this](u32, u32 val) {
                   m_Control.Hex = val;

                   if (m_Control.TSTART)
                   {
                     IEXIDevice* pDevice = GetDevice(m_Status.CHIP_SELECT);
                     if (pDevice == nullptr)
                       return;

                     if (m_Control.DMA == 0)
                     {
                       // immediate data
                       switch (m_Control.RW)
                       {
                       case EXI_READ:
                         m_ImmData = pDevice->ImmRead(m_Control.TLEN + 1);
                         break;
                       case EXI_WRITE:
                         pDevice->ImmWrite(m_ImmData, m_Control.TLEN + 1);
                         break;
                       case EXI_READWRITE:
                         pDevice->ImmReadWrite(m_ImmData, m_Control.TLEN + 1);
                         break;
                       default:
                         _dbg_assert_msg_(EXPANSIONINTERFACE, 0,
                                          "EXI Imm: Unknown transfer type %i", m_Control.RW);
                       }
                     }
                     else
                     {
                       // DMA
                       switch (m_Control.RW)
                       {
                       case EXI_READ:
                         pDevice->DMARead(m_DMAMemoryAddress, m_DMALength);
                         break;
                       case EXI_WRITE:
                         pDevice->DMAWrite(m_DMAMemoryAddress, m_DMALength);
                         break;
                       default:
                         _dbg_assert_msg_(EXPANSIONINTERFACE, 0,
                                          "EXI DMA: Unknown transfer type %i", m_Control.RW);
                       }
                     }

                     m_Control.TSTART = 0;

                     // Check if device needs specific timing, otherwise just complete transfer
                     // immediately
                     if (!pDevice->UseDelayedTransferCompletion())
                       SendTransferComplete();
                   }
                 }));

  mmio->Register(base + EXI_IMMDATA, MMIO::DirectRead<u32>(&m_ImmData),
                 MMIO::DirectWrite<u32>(&m_ImmData));
}
Пример #23
0
// use this function to render the GL surface on the device, using any modification you want
// return S_OK if you actually draw the texture on the device, or S_FALSE to let VirtualDJ do it
// if using VDJPLUGINFLAG_VIDEOINPLACE, texture and vertices will be NULL
HRESULT __stdcall SpoutSenderPlugin::OnDraw()
{
	TVertex *vertices;

	// Quit if OpenGL initialization failed
	if(!bOpenGL) { 
		DrawDeck(); 
		return S_OK; 
	}

	// Activate the shared context for draw
	// This can fail if the video window is closed and re-opened
	// Possibly because the dc that was orginally used is gone
	// It will start again if the start button is toggled
	// but calling StartOpenGL here seems to work OK.
	if(!wglMakeCurrent(m_hdc, m_hSharedRC)) {
		// printf("wglMakeCurrent 1 fail\n");
		bOpenGL = false;
		StartOpenGL(); // Initialize openGL again
		return S_OK;
	}

	// In order to draw the original image, you can either just call DrawDeck()
	// if you don't need to modify the image (for overlay plugins for examples),
	// or call GetTexture to get low-level access to the texture and its vertices.

	// Get the DX9 device
	GetDevice(VdjVideoEngineDirectX9, (void **)&d3d_device);
	if(d3d_device) {

		// Get the Virtual DJ texture and description
		GetTexture(VdjVideoEngineDirectX9, (void **)&dxTexture, &vertices);
		dxTexture->GetLevelDesc(0, &desc);
		if(!dxTexture) {
			DrawDeck(); // Let VirtualDJ do the drawing
		    return S_OK;
		}

		// Is Spout initialized yet ?
		if(!bInitialized) {
			m_Width = desc.Width;
			m_Height = desc.Height;

			// This is a sender so create one
			sprintf_s(SenderName, 256, "VirtualDJ Spout Sender");

			// To use DirectX 9 we need to specify that first
			spoutsender.SetDX9(true);

			// And we also have to set the shared texture format as D3DFMT_X8R8G8B8 so that receivers know it
			// because the default format argument is zero and that assumes D3DFMT_A8R8G8B8
			if(spoutsender.CreateSender(SenderName, m_Width, m_Height, (DWORD)D3DFMT_X8R8G8B8)) {
				// printf("Created sender [%s]\n", SenderName);
				bInitialized = true;
			}


		}
		else if(m_Width != desc.Width || m_Height != desc.Height) {

			// Initialized but has the texture changed size ?
			m_Width = desc.Width;
			m_Height = desc.Height;

			// Update the sender	
			spoutsender.UpdateSender(SenderName, m_Width, m_Height);

		}
		else if(bSpoutOut) { // Initialized and plugin has started

			// Copy from video memory to system memory
			hr = d3d_device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &source_surface, NULL);
			if(SUCCEEDED(hr)) {
				
				// Get the Virtual DJ texture Surface
				hr = dxTexture->GetSurfaceLevel(0, &texture_surface);

				if(SUCCEEDED(hr)) {
					// Copy Surface to Surface
					hr = d3d_device->GetRenderTargetData(texture_surface, source_surface);	
					if(SUCCEEDED(hr)) {
						// Lock the source surface using some flags for optimization
						hr = source_surface->LockRect(&d3dlr, NULL, D3DLOCK_NO_DIRTY_UPDATE | D3DLOCK_READONLY);
						if(SUCCEEDED(hr)) {
							source_surface->GetDesc(&desc);
							// Pass the pixels to spout
							// Disable invert of texture because this is a DirectX source
							// 4-byte alignment might need checking
							if(desc.Format == D3DFMT_X8R8G8B8) { // We have initialized the sender for this format
								spoutsender.SendImage((unsigned char *)d3dlr.pBits, desc.Width, desc.Height, GL_BGRA_EXT, true, false);
							}
							source_surface->UnlockRect();
						}
					}
				}
			}

			if(texture_surface) texture_surface->Release();
			if(source_surface) source_surface->Release();
			texture_surface = NULL;
			source_surface = NULL;

		}
	}

	DrawDeck(); // Draw the image coming in

	return S_OK;

}
Пример #24
0
boolean CUSBBluetoothDevice::Configure (void)
{
	if (GetInterfaceNumber () != 0)
	{
		CLogger::Get ()->Write (FromBluetooth, LogWarning, "Voice channels are not supported");

		return FALSE;
	}

	if (GetNumEndpoints () != 3)
	{
		ConfigurationError (FromBluetooth);

		return FALSE;
	}

	const TUSBEndpointDescriptor *pEndpointDesc;
	while ((pEndpointDesc = (TUSBEndpointDescriptor *) GetDescriptor (DESCRIPTOR_ENDPOINT)) != 0)
	{
		if ((pEndpointDesc->bmAttributes & 0x3F) == 0x02)		// Bulk
		{
			if ((pEndpointDesc->bEndpointAddress & 0x80) == 0x80)	// Input
			{
				if (m_pEndpointBulkIn != 0)
				{
					ConfigurationError (FromBluetooth);

					return FALSE;
				}

				m_pEndpointBulkIn = new CUSBEndpoint (GetDevice (), pEndpointDesc);
			}
			else							// Output
			{
				if (m_pEndpointBulkOut != 0)
				{
					ConfigurationError (FromBluetooth);

					return FALSE;
				}

				m_pEndpointBulkOut = new CUSBEndpoint (GetDevice (), pEndpointDesc);
			}
		}
		else if ((pEndpointDesc->bmAttributes & 0x3F) == 0x03)		// Interrupt
		{
			if (m_pEndpointInterrupt != 0)
			{
				ConfigurationError (FromBluetooth);

				return FALSE;
			}

			m_pEndpointInterrupt = new CUSBEndpoint (GetDevice (), pEndpointDesc);
		}
	}

	if (   m_pEndpointBulkIn    == 0
	    || m_pEndpointBulkOut   == 0
	    || m_pEndpointInterrupt == 0)
	{
		ConfigurationError (FromBluetooth);

		return FALSE;
	}

	if (!CUSBFunction::Configure ())
	{
		CLogger::Get ()->Write (FromBluetooth, LogError, "Cannot set interface");

		return FALSE;
	}

	m_pEventBuffer = new u8[m_pEndpointInterrupt->GetMaxPacketSize ()];
	assert (m_pEventBuffer != 0);

	CString DeviceName;
	DeviceName.Format ("ubt%u", s_nDeviceNumber++);
	CDeviceNameService::Get ()->AddDevice (DeviceName, this, FALSE);

	return TRUE;
}
bool CD3DBillBoardParticleEmitter::LoadFromResource(CD3DParticleEmitterResource * pModelResource,UINT MaxParticleCount)
{
	if(GetDevice()==NULL)
		return false;
	


	Destory();
	m_pModelResource=pModelResource;
	m_pModelResource->AddUseRef();
	m_MaxParticleCount=MaxParticleCount;

	SetName(m_pModelResource->GetName());

	CD3DParticleEmitterResource::PARTICLE_EMITTER_INFO * pEmitterInfo=m_pModelResource->GetParticleEmitterInfo();

	if(m_MaxParticleCount==0)
	{
		FLOAT MaxEmissionRate=0.0f;
		
		for(UINT i=0;i<pEmitterInfo->EmissionRate.Animations[0].Keys.GetCount();i++)
		{
			if(pEmitterInfo->EmissionRate.Animations[0].Keys[i]>MaxEmissionRate)
			{
				MaxEmissionRate=pEmitterInfo->EmissionRate.Animations[0].Keys[i];
			}
		}
		FLOAT MaxLifeSpan=0.0f;
		for(UINT i=0;i<pEmitterInfo->LifeSpan.Animations[0].Keys.GetCount();i++)
		{
			if(pEmitterInfo->LifeSpan.Animations[0].Keys[i]>MaxLifeSpan)
			{
				MaxLifeSpan=pEmitterInfo->LifeSpan.Animations[0].Keys[i];
			}
		}
		m_MaxParticleCount=(UINT)(MaxEmissionRate*MaxLifeSpan*2.0f);
	}
	
	if(m_MaxParticleCount>MAX_PARTICLE_COUNT)
		m_MaxParticleCount=MAX_PARTICLE_COUNT;	
	if(m_MaxParticleCount<MIN_PARTICLE_COUNT)
		m_MaxParticleCount=MIN_PARTICLE_COUNT;
	m_pParticleVertexBuffer=new PARTICLE_RECT[m_MaxParticleCount];
	m_pParticleIndexBuffer=new WORD[m_MaxParticleCount*6];

	D3DVERTEXELEMENT9 ParticleVertexElements[] = 
	{
		{0, 0,  D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_POSITION,	0},
		{0, 16, D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_NORMAL,	0},
		{0, 32, D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_COLOR,		0},
		{0, 48, D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_COLOR,		1},		
		{0, 64, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	0},
		{0, 68, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	1},
		{0, 72, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	2},
		{0, 76, D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	3},
		{0, 92,	D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	4},
		{0, 108, D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	5},
		{0, 124, D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	6},
		{0, 140, D3DDECLTYPE_FLOAT4,   D3DDECLMETHOD_DEFAULT,		D3DDECLUSAGE_TEXCOORD,	7},
		D3DDECL_END()
	};

	m_SubMesh.SetDevice(GetDevice());
	m_SubMesh.DeclareVertexFormat(ParticleVertexElements,sizeof(PARTICLE_VERTEX),sizeof(WORD));
	m_SubMesh.SetPrimitiveType(D3DPT_TRIANGLELIST);	
	m_SubMesh.SetVertices((BYTE *)m_pParticleVertexBuffer);
	m_SubMesh.SetIndices((BYTE *)m_pParticleIndexBuffer);
	m_SubMesh.SetRenderBufferUsed(CD3DSubMesh::BUFFER_USE_CUSTOM);
	m_SubMesh.SetVertexCount(m_MaxParticleCount*4);
	m_SubMesh.SetIndexCount(m_MaxParticleCount*6);
	m_SubMesh.AllocVertexBufferR();
	m_SubMesh.AllocIndexBufferR();
	m_SubMesh.SetVertexCount(0);
	m_SubMesh.SetIndexCount(0);
	m_SubMesh.AddProperty(CD3DSubMesh::SMF_IS_ANI_MESH);
	for(UINT i=0;i<m_MaxParticleCount;i++)
	{
		
		m_pParticleVertexBuffer[i].Vertex[0].Tex.x=0.0f;
		m_pParticleVertexBuffer[i].Vertex[0].Tex.y=0.0f;
		m_pParticleVertexBuffer[i].Vertex[1].Tex.x=1.0f;
		m_pParticleVertexBuffer[i].Vertex[1].Tex.y=0.0f;
		m_pParticleVertexBuffer[i].Vertex[2].Tex.x=0.0f;
		m_pParticleVertexBuffer[i].Vertex[2].Tex.y=1.0f;
		m_pParticleVertexBuffer[i].Vertex[3].Tex.x=1.0f;
		m_pParticleVertexBuffer[i].Vertex[3].Tex.y=1.0f;			
		
		m_pParticleIndexBuffer[i*6]=i*4;
		m_pParticleIndexBuffer[i*6+1]=i*4+1;
		m_pParticleIndexBuffer[i*6+2]=i*4+2;
		m_pParticleIndexBuffer[i*6+3]=i*4+2;
		m_pParticleIndexBuffer[i*6+4]=i*4+1;
		m_pParticleIndexBuffer[i*6+5]=i*4+3;
	}

	D3DCOLORVALUE WhiteColor={1.0f,1.0f,1.0f,1.0f};
	D3DCOLORVALUE GrayColor={0.8f,0.8f,0.8f,1.0f};
	D3DCOLORVALUE BlackColor={0.0f,0.0f,0.0f,1.0f};

	m_SubMesh.GetMaterial().GetMaterial().Ambient=WhiteColor;
	m_SubMesh.GetMaterial().GetMaterial().Diffuse=WhiteColor;
	m_SubMesh.GetMaterial().GetMaterial().Specular=WhiteColor;
	m_SubMesh.GetMaterial().GetMaterial().Emissive=BlackColor;
	m_SubMesh.GetMaterial().GetMaterial().Power=40.0f;


	m_SubMesh.GetMaterial().AddTexture(pEmitterInfo->pTexture,0,"TexLay0","");
	if(pEmitterInfo->pTexture)
		pEmitterInfo->pTexture->AddUseRef();
	m_SubMesh.GetMaterial().SetFX(pEmitterInfo->pFX);
	if(pEmitterInfo->pFX)
		pEmitterInfo->pFX->AddUseRef();

	if(pEmitterInfo->BlendingType!=EBT_OPACITY&&pEmitterInfo->BlendingType!=EBT_ALPHA_TEST)
	{
		m_SubMesh.SetTransparent(true);
	}

	m_SubMesh.GetMaterial().CaculateHashCode();

	if(pEmitterInfo->Flags&CD3DParticleEmitterResource::PEF_GRAVITY_TRANSFORM)
	{
		m_EnbaleGravityTransform=true;
	}
	else
	{
		m_EnbaleGravityTransform=false;
	}

	m_NoTrail=((pEmitterInfo->Flags&CD3DParticleEmitterResource::PEF_NO_TRAIL)!=0);
	m_TextureTileRotation=pEmitterInfo->TextureTileRotation;

	m_ParticleCount=0;

	CreateBoundings();

	return true;
}
Пример #26
0
boolean CSMSC951xDevice::Configure (void)
{
	CBcmPropertyTags Tags;
	TPropertyTagMACAddress MACAddress;
	if (Tags.GetTag (PROPTAG_GET_MAC_ADDRESS, &MACAddress, sizeof MACAddress))
	{
		m_MACAddress.Set (MACAddress.Address);
	}
	else
	{
		CLogger::Get ()->Write (FromSMSC951x, LogError, "Cannot get MAC address");

		return FALSE;
	}
	CString MACString;
	m_MACAddress.Format (&MACString);
	CLogger::Get ()->Write (FromSMSC951x, LogDebug, "MAC address is %s", (const char *) MACString);

	if (GetNumEndpoints () != 3)
	{
		ConfigurationError (FromSMSC951x);

		return FALSE;
	}

	const TUSBEndpointDescriptor *pEndpointDesc;
	while ((pEndpointDesc = (TUSBEndpointDescriptor *) GetDescriptor (DESCRIPTOR_ENDPOINT)) != 0)
	{
		if ((pEndpointDesc->bmAttributes & 0x3F) == 0x02)		// Bulk
		{
			if ((pEndpointDesc->bEndpointAddress & 0x80) == 0x80)	// Input
			{
				if (m_pEndpointBulkIn != 0)
				{
					ConfigurationError (FromSMSC951x);

					return FALSE;
				}

				m_pEndpointBulkIn = new CUSBEndpoint (GetDevice (), pEndpointDesc);
			}
			else							// Output
			{
				if (m_pEndpointBulkOut != 0)
				{
					ConfigurationError (FromSMSC951x);

					return FALSE;
				}

				m_pEndpointBulkOut = new CUSBEndpoint (GetDevice (), pEndpointDesc);
			}
		}
	}

	if (   m_pEndpointBulkIn  == 0
	    || m_pEndpointBulkOut == 0)
	{
		ConfigurationError (FromSMSC951x);

		return FALSE;
	}

	if (!CUSBFunction::Configure ())
	{
		CLogger::Get ()->Write (FromSMSC951x, LogError, "Cannot set interface");

		return FALSE;
	}

	u8 MACAddressBuffer[MAC_ADDRESS_SIZE];
	m_MACAddress.CopyTo (MACAddressBuffer);
	u16 usMACAddressHigh =   (u16) MACAddressBuffer[4]
			       | (u16) MACAddressBuffer[5] << 8;
	u32 nMACAddressLow   =   (u32) MACAddressBuffer[0]
			       | (u32) MACAddressBuffer[1] << 8
			       | (u32) MACAddressBuffer[2] << 16
			       | (u32) MACAddressBuffer[3] << 24;
	if (   !WriteReg (ADDRH, usMACAddressHigh)
	    || !WriteReg (ADDRL, nMACAddressLow))
	{
		CLogger::Get ()->Write (FromSMSC951x, LogError, "Cannot set MAC address");

		return FALSE;
	}

	if (   !WriteReg (LED_GPIO_CFG,   LED_GPIO_CFG_SPD_LED
					| LED_GPIO_CFG_LNK_LED
					| LED_GPIO_CFG_FDX_LED)
	    || !WriteReg (MAC_CR,  MAC_CR_RCVOWN
				 //| MAC_CR_PRMS		// promiscous mode
				 | MAC_CR_TXEN
				 | MAC_CR_RXEN)
	    || !WriteReg (TX_CFG, TX_CFG_ON))
	{
		CLogger::Get ()->Write (FromSMSC951x, LogError, "Cannot start device");

		return FALSE;
	}

	AddNetDevice ();

	return TRUE;
}
Пример #27
0
boolean CUSBHIDDevice::Configure (unsigned nMaxReportSize)
{
	if (GetNumEndpoints () < 1)
	{
		ConfigurationError (FromUSBHID);

		return FALSE;
	}

	const TUSBEndpointDescriptor *pEndpointDesc;
	while ((pEndpointDesc = (TUSBEndpointDescriptor *) GetDescriptor (DESCRIPTOR_ENDPOINT)) != 0)
	{
		if ((pEndpointDesc->bmAttributes & 0x3F) == 0x03)		// Interrupt EP
		{
			if ((pEndpointDesc->bEndpointAddress & 0x80) == 0x80)	// Input EP
			{
				if (m_pReportEndpoint != 0)
				{
					ConfigurationError (FromUSBHID);

					return FALSE;
				}

				m_pReportEndpoint = new CUSBEndpoint (GetDevice (), pEndpointDesc);
			}
			else							// Output EP
			{
				if (m_pEndpointOut != 0)
				{
					ConfigurationError (FromUSBHID);

					return FALSE;
				}

				m_pEndpointOut = new CUSBEndpoint (GetDevice (), pEndpointDesc);
			}
		}
	}

	if (m_pReportEndpoint == 0)
	{
		ConfigurationError (FromUSBHID);

		return FALSE;
	}

	if (!CUSBFunction::Configure ())
	{
		CLogger::Get ()->Write (FromUSBHID, LogError, "Cannot set interface");

		return FALSE;
	}

	if (   GetInterfaceClass ()    == 3	// HID class
	    && GetInterfaceSubClass () == 1)	// boot class
	{
		if (GetHost ()->ControlMessage (GetEndpoint0 (),
						REQUEST_OUT | REQUEST_CLASS | REQUEST_TO_INTERFACE,
						SET_PROTOCOL, BOOT_PROTOCOL,
						GetInterfaceNumber (), 0, 0) < 0)
		{
			CLogger::Get ()->Write (FromUSBHID, LogError, "Cannot set boot protocol");

			return FALSE;
		}
	}

	if (m_nMaxReportSize == 0)
	{
		m_nMaxReportSize = nMaxReportSize;
		assert (m_nMaxReportSize > 0);

		assert (m_pReportBuffer == 0);
		m_pReportBuffer = new u8[m_nMaxReportSize];
	}
	assert (m_pReportBuffer != 0);

	return TRUE;
}
Пример #28
0
int main(int argc, char** argv)
{
	cl_int err;
	int usegpu = USEGPU;
    int do_verify = 0;
    int opt, option_index=0;

    unsigned int correct;

    size_t global_size;
    size_t local_size;

    cl_device_id device_id;
    cl_context context;
    cl_command_queue commands;
    cl_program program;
    cl_kernel kernel;

    stopwatch sw;

    cl_mem csr_ap;
    cl_mem csr_aj;
    cl_mem csr_ax;
    cl_mem x_loc;
    cl_mem y_loc;

    FILE *kernelFile;
    char *kernelSource;
    size_t kernelLength;
    size_t lengthRead;


    ocd_init(&argc, &argv, NULL);
    ocd_options opts = ocd_get_options();
    platform_id = opts.platform_id;
    n_device = opts.device_id;

    while ((opt = getopt_long(argc, argv, "::vc::", 
                            long_options, &option_index)) != -1 ) {
      switch(opt){
        //case 'i':
          //input_file = optarg;
          //break;
        case 'v':
          fprintf(stderr, "verify\n");
          do_verify = 1;
          break;
        case 'c':
          fprintf(stderr, "using cpu\n");
          usegpu = 0;
	  break;
        default:
          fprintf(stderr, "Usage: %s [-v Warning: lots of output] [-c use CPU]\n",
                  argv[0]);
          exit(EXIT_FAILURE);
      }
  }

    /* Fill input set with random float values */
    int i;

    csr_matrix csr;
    csr = laplacian_5pt(512);
    int k = 0;
      for(k = 0; k < csr.num_nonzeros; k++){
         csr.Ax[k] = 1.0 - 2.0 * (rand() / (RAND_MAX + 1.0));
      }

    //The other arrays
    float * x_host = float_new_array(csr.num_cols);
    float * y_host = float_new_array(csr.num_rows);

    unsigned int ii;
    for(ii = 0; ii < csr.num_cols; ii++){
        x_host[ii] = rand() / (RAND_MAX + 1.0);
    }
    for(ii = 0; ii < csr.num_rows; ii++){
        y_host[ii] = rand() / (RAND_MAX + 2.0);
    }

    /* Retrieve an OpenCL platform */
    device_id = GetDevice(platform_id, n_device);

    /* Create a compute context */
    context = clCreateContext(0, 1, &device_id, NULL, NULL, &err);
    CHKERR(err, "Failed to create a compute context!");

    /* Create a command queue */
    commands = clCreateCommandQueue(context, device_id, CL_QUEUE_PROFILING_ENABLE, &err);
    CHKERR(err, "Failed to create a command queue!");

    /* Load kernel source */
    kernelFile = fopen("spmv_csr_kernel.cl", "r");
    fseek(kernelFile, 0, SEEK_END);
    kernelLength = (size_t) ftell(kernelFile);
    kernelSource = (char *) malloc(sizeof(char)*kernelLength);
    rewind(kernelFile);
    lengthRead = fread((void *) kernelSource, kernelLength, 1, kernelFile);
    fclose(kernelFile);

    /* Create the compute program from the source buffer */
    program = clCreateProgramWithSource(context, 1, (const char **) &kernelSource, &kernelLength, &err);
    CHKERR(err, "Failed to create a compute program!");

    /* Free kernel source */
    free(kernelSource);

    /* Build the program executable */
    err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
    if (err == CL_BUILD_PROGRAM_FAILURE)                                                                                                                                       
    {
        char *buildLog;
        size_t logLen;
        err = clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &logLen);
        buildLog = (char *) malloc(sizeof(char)*logLen);
        err = clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, logLen, (void *) buildLog, NULL);
        fprintf(stderr, "CL Error %d: Failed to build program! Log:\n%s", err, buildLog);
        free(buildLog);
        exit(1);
    }
    CHKERR(err, "Failed to build program!");

    /* Create the compute kernel in the program we wish to run */
    kernel = clCreateKernel(program, "csr", &err);
    CHKERR(err, "Failed to create a compute kernel!");

    /* Create the input and output arrays in device memory for our calculation */
    csr_ap = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(unsigned int)*csr.num_rows+4, NULL, &err);
    CHKERR(err, "Failed to allocate device memory!");
    csr_aj = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(unsigned int)*csr.num_nonzeros, NULL, &err);
    CHKERR(err, "Failed to allocate device memory!");
    csr_ax = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*csr.num_nonzeros, NULL, &err);
    CHKERR(err, "Failed to allocate device memory!");
    x_loc = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*csr.num_cols, NULL, &err);
    CHKERR(err, "Failed to allocate device memory!");
    y_loc = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float)*csr.num_rows, NULL, &err);
    CHKERR(err, "Failed to allocate device memory!");

    /* beginning of timing point */
    stopwatch_start(&sw); 
   
    /* Write our data set into the input array in device memory */
	err = clEnqueueWriteBuffer(commands, csr_ap, CL_TRUE, 0, sizeof(unsigned int)*csr.num_rows+4, csr.Ap, 0, NULL, &ocdTempEvent);
        clFinish(commands);
	START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "CSR Data Copy", ocdTempTimer)
	END_TIMER(ocdTempTimer)
    CHKERR(err, "Failed to write to source array!");
    err = clEnqueueWriteBuffer(commands, csr_aj, CL_TRUE, 0, sizeof(unsigned int)*csr.num_nonzeros, csr.Aj, 0, NULL, &ocdTempEvent);
        clFinish(commands);
	START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "CSR Data Copy", ocdTempTimer)
	END_TIMER(ocdTempTimer)
    CHKERR(err, "Failed to write to source array!");
    err = clEnqueueWriteBuffer(commands, csr_ax, CL_TRUE, 0, sizeof(float)*csr.num_nonzeros, csr.Ax, 0, NULL, &ocdTempEvent);
        clFinish(commands);
	START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "CSR Data Copy", ocdTempTimer)
	END_TIMER(ocdTempTimer)
    CHKERR(err, "Failed to write to source array!");
    err = clEnqueueWriteBuffer(commands, x_loc, CL_TRUE, 0, sizeof(float)*csr.num_cols, x_host, 0, NULL, &ocdTempEvent);
        clFinish(commands);
	START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "CSR Data Copy", ocdTempTimer)
	END_TIMER(ocdTempTimer)
    CHKERR(err, "Failed to write to source array!");
    err = clEnqueueWriteBuffer(commands, y_loc, CL_TRUE, 0, sizeof(float)*csr.num_rows, y_host, 0, NULL, &ocdTempEvent);
        clFinish(commands);
	START_TIMER(ocdTempEvent, OCD_TIMER_H2D, "CSR Data Copy", ocdTempTimer)
    CHKERR(err, "Failed to write to source array!");
	END_TIMER(ocdTempTimer)
    /* Set the arguments to our compute kernel */
    err = 0;
    err = clSetKernelArg(kernel, 0, sizeof(unsigned int), &csr.num_rows);
    err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &csr_ap);
    err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &csr_aj);
    err |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &csr_ax);
    err |= clSetKernelArg(kernel, 4, sizeof(cl_mem), &x_loc);
    err |= clSetKernelArg(kernel, 5, sizeof(cl_mem), &y_loc);
    CHKERR(err, "Failed to set kernel arguments!");

    /* Get the maximum work group size for executing the kernel on the device */
    err = clGetKernelWorkGroupInfo(kernel, device_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), (void *) &local_size, NULL);
    CHKERR(err, "Failed to retrieve kernel work group info!");

    /* Execute the kernel over the entire range of our 1d input data set */
    /* using the maximum number of work group items for this device */
    global_size = csr.num_rows;
    err = clEnqueueNDRangeKernel(commands, kernel, 1, NULL, &global_size, &local_size, 0, NULL, &ocdTempEvent);
        clFinish(commands);
	START_TIMER(ocdTempEvent, OCD_TIMER_KERNEL, "CSR Kernel", ocdTempTimer)
    END_TIMER(ocdTempTimer)
    CHKERR(err, "Failed to execute kernel!");

    /* Wait for the command commands to get serviced before reading back results */
    float output[csr.num_rows];
    
    /* Read back the results from the device to verify the output */
	err = clEnqueueReadBuffer(commands, y_loc, CL_TRUE, 0, sizeof(float)*csr.num_rows, output, 0, NULL, &ocdTempEvent);
        clFinish(commands);
    	START_TIMER(ocdTempEvent, OCD_TIMER_D2H, "CSR Data Copy", ocdTempTimer)
	END_TIMER(ocdTempTimer)
	CHKERR(err, "Failed to read output array!");

    /* end of timing point */
    stopwatch_stop(&sw);
    printf("Time consumed(ms): %lf Gflops: %f \n", 1000*get_interval_by_sec(&sw), (2.0 * (double) csr.num_nonzeros / get_interval_by_sec(&sw)) / 1e9);

   /* Validate our results */
   if(do_verify){
       for (i = 0; i < csr.num_rows; i++){
           printf("row: %d	output: %f \n", i, output[i]);  
       }
   }

   int row = 0;
   float sum = 0;
   int row_start = 0;
   int row_end = 0;
   for(row =0; row < csr.num_rows; row++){     
        sum = y_host[row];
        
        row_start = csr.Ap[row];
        row_end   = csr.Ap[row+1];
        
        unsigned int jj = 0;
        for (jj = row_start; jj < row_end; jj++){             
            sum += csr.Ax[jj] * x_host[csr.Aj[jj]];      
        }
        y_host[row] = sum;
    }
    for (i = 0; i < csr.num_rows; i++){
        if((fabsf(y_host[i]) - fabsf(output[i])) > .001)
             printf("Possible error, difference greater then .001 at row %d \n", i);
    }

    /* Print a brief summary detailing the results */
    ocd_finalize();

    /* Shutdown and cleanup */
    clReleaseMemObject(csr_ap);
    clReleaseMemObject(csr_aj);
    clReleaseMemObject(csr_ax);
    clReleaseMemObject(x_loc);
    clReleaseMemObject(y_loc);
    clReleaseProgram(program);
    clReleaseKernel(kernel);
    clReleaseCommandQueue(commands);
    clReleaseContext(context);
    return 0;
}
Пример #29
0
bool XMeshData::Init(const std::wstring& FilePath) {
    Node::Init();

    // 재질을 임시로 보관할 버퍼선언
    LPD3DXBUFFER pD3DXMtrlBuffer;

    mEffect = ResourceManager::GetInstance()->LoadHLSL(L"Shader\\SkinnedMesh.fx");
    if (!mEffect) {
        MessageBox(NULL, L"Could not HLSL file", L"ERROR", MB_OK);
        assert(false);
        return false;
    }

    if (FAILED(D3DXLoadMeshFromX(FilePath.c_str(), D3DXMESH_SYSTEMMEM,
                                 GetDevice(), NULL,
                                 &pD3DXMtrlBuffer, NULL, &mNumMaterial,
                                 &mXMesh)))
    {
        MessageBox(NULL, L"Could not find mesh file", L"ERROR", MB_OK);
        return false;
    }

    // 재질정보와 텍스쳐 정보를 따로 뽑아낸다.
    D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();
    mMaterial = new D3DMATERIAL9[mNumMaterial];			// 재질개수만큼 재질구조체 배열 생성
    mTexture = new LPDIRECT3DTEXTURE9[mNumMaterial];	// 재질개수만큼 텍스쳐 배열 생성

    for (DWORD j = 0; j<mNumMaterial; j++) {
        // 재질정보를 복사
        mMaterial[j] = d3dxMaterials[j].MatD3D;

        // 주변광원정보를 Diffuse정보로
        mMaterial[j].Ambient = mMaterial[j].Diffuse;

        mTexture[j] = NULL;

        if (d3dxMaterials[j].pTextureFilename != NULL &&
                strlen(d3dxMaterials[j].pTextureFilename) > 0)
        {
            // 텍스쳐를 파일에서 로드한다
            // w로 통일할껀지 정해야함
            std::string FileName = "Model\\";
            FileName += d3dxMaterials[j].pTextureFilename;

            if (FAILED(D3DXCreateTextureFromFileA(GetDevice(),
                                                  FileName.c_str(),
                                                  &mTexture[j])))
            {
                MessageBox(NULL, L"Could not find texture map", L"ERROR", MB_OK);
                assert(false);

                return false;
            }
        }
    }
    SAFE_RELEASE( pD3DXMtrlBuffer );

    //메쉬에 법선백터를 추가하는 부분
    if (!(mXMesh->GetFVF() & D3DFVF_NORMAL)) {
        //가지고 있지 않다면 메쉬를 복제하고 D3DFVF_NORMAL을 추가한다.
        ID3DXMesh* pTempMesh = 0;

        mXMesh->CloneMeshFVF(D3DXMESH_MANAGED,
                             mXMesh->GetFVF() | D3DFVF_NORMAL,  //이곳에 추가
                             GetDevice(),
                             &pTempMesh);

        // 법선을 계산한다.
        D3DXComputeNormals(pTempMesh, 0);

        mXMesh->Release(); // 기존메쉬를 제거한다
        mXMesh = pTempMesh; // 기존메쉬를 법선이 계산된 메쉬로 지정한다.
    }

    // Init Vertices and Indices

    int VerticesNum = mXMesh->GetNumVertices();
    BYTE* vertexBuffer;
    DWORD numBytesPerVertex = mXMesh->GetNumBytesPerVertex();
    unsigned int offset = D3DXGetFVFVertexSize(mXMesh->GetFVF());

    mXMesh->LockVertexBuffer(D3DLOCK_READONLY, (void**)&vertexBuffer);
    for (WORD i = 0; i < VerticesNum; i++)
        mVertices.push_back(*((D3DXVECTOR3*)(vertexBuffer + i * offset)));
    mXMesh->UnlockVertexBuffer();


    void *pIB;
    int IndicesNum = mXMesh->GetNumFaces();
    WORD *indexBuffer = new WORD[IndicesNum * 3];

    mXMesh->LockIndexBuffer(D3DLOCK_READONLY, (void**)&pIB);
    memcpy(indexBuffer, pIB, sizeof(WORD)*IndicesNum * 3);

    for (int i = 0; i < IndicesNum; ++i)
        mIndices.push_back(D3DXVECTOR3(indexBuffer[i * 3], indexBuffer[i * 3 + 1], indexBuffer[i * 3 + 2]));

    mXMesh->UnlockIndexBuffer();
    delete[]indexBuffer;

    return true;
}
Пример #30
0
/******************************************************************************
* 関数名:InitPause
* 
* 引数  :
* 戻り値:
* 説明  :
******************************************************************************/
HRESULT InitPause( void )
{
	LPDIRECT3DDEVICE9 pDevice = GetDevice();//mainでのg_pD3DDevice

	for( int cnt = 0 ; cnt < PAUSE_TEX_MAX ; cnt++ )
	{
		if( FAILED ( pDevice -> CreateVertexBuffer( sizeof( VERTEX_2D ) * 4 ,
													D3DUSAGE_WRITEONLY ,
													FVF_VERTEX_2D ,
													D3DPOOL_MANAGED ,
													&g_pause[cnt].pVtxBuffPause ,
													NULL ) ) )
		{
			return E_FAIL;
		}
	}

	g_pausePattarn = PAUSE_CONTINUE;	//ポーズパターンの初期値

	g_bPause = false;

	//テクスチャ読み込み
	D3DXCreateTextureFromFile( pDevice , PAUSE_BG_NAME , &g_pTexturePause[0] );
	D3DXCreateTextureFromFile( pDevice , "data/TEXTURE/pause000.png" , &g_pTexturePause[1] );
	D3DXCreateTextureFromFile( pDevice , "data/TEXTURE/pause001.png" , &g_pTexturePause[2] );
	D3DXCreateTextureFromFile( pDevice , "data/TEXTURE/pause002.png" , &g_pTexturePause[3] );


	for( int cnt = 0 ; cnt < PAUSE_TEX_MAX ; cnt++ )
	{

		VERTEX_2D *pVtx;
		g_pause[cnt].pVtxBuffPause -> Lock( 0 , 0 , ( void** ) &pVtx , 0 );


		g_pause[0].pos    = D3DXVECTOR3( SCREEN_WIDTH / 2 , SCREEN_HEIGHT /2 , 0.0f );
		g_pause[0].height = PAUSE_BG_HEIGHT / 2;
		g_pause[0].width  = PAUSE_BG_WIDTH  / 2;

		g_pause[1].pos    = D3DXVECTOR3( SCREEN_WIDTH / 2 , SCREEN_HEIGHT / 2 - 100 , 0.0f );
		g_pause[1].height = PAUSE_LOGO1_HEIGHT / 2;
		g_pause[1].width  = PAUSE_LOGO1_WIDTH / 2;

		g_pause[2].pos    = D3DXVECTOR3( SCREEN_WIDTH / 2 , SCREEN_HEIGHT / 2 , 0.0f );
		g_pause[2].height = PAUSE_LOGO2_HEIGHT / 2;
		g_pause[2].width  = PAUSE_LOGO2_WIDTH  / 2;

		g_pause[3].pos    = D3DXVECTOR3( SCREEN_WIDTH / 2 , SCREEN_HEIGHT / 2 + 100, 0.0f );
		g_pause[3].height = PAUSE_LOGO3_HEIGHT / 2;
		g_pause[3].width  = PAUSE_LOGO3_WIDTH / 2;

		//座標設定
		pVtx[0].pos = D3DXVECTOR3( g_pause[cnt].pos.x - g_pause[cnt].width , g_pause[cnt].pos.y - g_pause[cnt].height , 0.0f );
		pVtx[1].pos = D3DXVECTOR3( g_pause[cnt].pos.x + g_pause[cnt].width , g_pause[cnt].pos.y - g_pause[cnt].height , 0.0f );
		pVtx[2].pos = D3DXVECTOR3( g_pause[cnt].pos.x - g_pause[cnt].width , g_pause[cnt].pos.y + g_pause[cnt].height , 0.0f );
		pVtx[3].pos = D3DXVECTOR3( g_pause[cnt].pos.x + g_pause[cnt].width , g_pause[cnt].pos.y + g_pause[cnt].height , 0.0f );


		//2次元変数
		pVtx[0].rwh = 1.0f;
		pVtx[1].rwh = 1.0f;
		pVtx[2].rwh = 1.0f;
		pVtx[3].rwh = 1.0f;

		//頂点カラー設定
		for( int cntCol = 0 ; cntCol < 4 ; cntCol ++ )
		{
			pVtx[cntCol].col = D3DCOLOR_RGBA( 255 , 255 , 255 , 255 );
		}

		//テクスチャ
		pVtx[0].tex = D3DXVECTOR2( 0 , 0 );
		pVtx[1].tex = D3DXVECTOR2( 1 , 0 );
		pVtx[2].tex = D3DXVECTOR2( 0 , 1 );
		pVtx[3].tex = D3DXVECTOR2( 1 , 1 );

		g_pause[cnt].pVtxBuffPause -> Unlock();

	}

	return S_OK;
}