Page 5 of 5

Re: Windows8, WinRT, WOA & Metro

Posted: Wed Mar 05, 2014 10:43 pm
by KungFooMasta
True. What I did is get a pointer to the MeshManager and just view it in the debugger to see how many resources it has. It only has the 3 prefab meshes that are created on initialization. I'm thinking I might need to hand it a full path of the package directory, I'll try and dig a little more when I get a chance. I don't understand how the browser winrt sample can access all the media, they're linked to in the project, but I don't think the resources.cfg references the resources, and I don't see where the resource paths would be added via code. In the worst case I'd have to get the browser winrt running and step through it, hopefully I can figure this out before then.

Re: Windows8, WinRT, WOA & Metro

Posted: Thu Mar 06, 2014 11:59 pm
by KungFooMasta
I'm not able to get the SampleBrowserWinRT running, I added in a bunch of libs and include directories, but now I'm stuck with the following errors:
Error 135 error APPX0702: Payload file 'D:\Sandbox\Ogre\Samples\Media\thumbnails\thumb_tesselation.png' does not exist. C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\AppxPackage\Microsoft.AppXPackage.Targets 1395 9 SampleBrowserWinRT
On the other hand, I was able to validate that files listed in the "Assets" folder in my Visual Studio project are detected with the following line of code:

Code: Select all

Ogre::ResourceGroupManager::getSingleton().addResourceLocation(".\\Assets\\", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
Success! I was able to create an entity using the ogrehead.mesh file I added to my project's Assets folder. However now I get problems trying to render the ogre head:
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Attempted to render to a D3D11 device without both vertex and fragment shaders there is no fixed pipeline in d3d11 - use the RTSS or write custom shaders.",
"D3D11RenderSystem::_render");
Now on to figuring out the RTShaderSystem, which is almost completely foreign to me. :cry:

Re: Windows8, WinRT, WOA & Metro

Posted: Fri Mar 07, 2014 3:19 am
by KungFooMasta
Ok, turns out the RTShaderSystem isn't so bad, thanks to the BrowserWinRT code. One thing I learned was that I was missing some of the .hlsl files that are used by the provided use of RTSS. Please let me know if I'm missing any files, but I believe these are the files that need to be included:
FFPLib_Common.hlsl
FFPLib_Fog.hlsl
FFPLib_Lighting.hlsl
FFPLib_Texturing.hlsl
FFPLib_Transform.hlsl
I think I have everything setup as it needs to be, however I have some real issues now. I am able to use the ShaderGenerator to create BaseWhite and BaseWhitNoLighting materials for use, and they even work, however when I try to actually render the Ogre head using more complex materials, and by complex I mean actually texturing the Ogre, I am getting some huge complaints from Ogre/RTSS.
17:49:56: OGRE EXCEPTION(3:RenderingAPIException): Cannot assemble D3D11 high-level shader 50287ee7-fc53-9c1f-7a7c-ff2526c05377_FS Errors:
D:\Sandbox\SampleOgreApp\Debug\SampleOgreApp\AppX\Shader@0x0785B6B0(41,2-73): error X3017: 'FFP_Construct_Sampler_Wrapper': cannot implicitly convert from 'const sampler2D' to 'TextureCube<float4>'
in D3D11HLSLProgram::loadFromSource at src\OgreD3D11HLSLProgram.cpp (line 502)
17:49:56: High-level program 50287ee7-fc53-9c1f-7a7c-ff2526c05377_FS encountered an error during loading and is thus not supported.
OGRE EXCEPTION(3:RenderingAPIException): Cannot assemble D3D11 high-level shader 50287ee7-fc53-9c1f-7a7c-ff2526c05377_FS Errors:
D:\Sandbox\SampleOgreApp\Debug\SampleOgreApp\AppX\Shader@0x0785B6B0(41,2-73): error X3017: 'FFP_Construct_Sampler_Wrapper': cannot implicitly convert from 'const sampler2D' to 'TextureCube<float4>'
in D3D11HLSLProgram::loadFromSource at src\OgreD3D11HLSLProgram.cpp (line 502)
17:49:56: OGRE EXCEPTION(2:InvalidParametersException): Could not create gpu programs from render state in ProgramManager::acquireGpuPrograms at src\OgreShaderProgramManager.cpp (line 109)
This actually looks like a problem with FFPLib_Texturing.hlsl. Unfortunately I don't know much about hlsl syntax and coding in that language, I have no idea how to fix this. It has to be simple, right? It's choking when trying to generate the "Ogre/Skin" material using vs_4_0 target.

Anybody help me out here? I have a feeling the hlsl is out of date.

Re: Windows8, WinRT, WOA & Metro

Posted: Fri Mar 07, 2014 8:15 am
by Jake007
At initial port to WinRT platform, Eugene, Cygon and the others stumbled at the same problem, but solved it with mBackwardsCompatiblity flag.
It's on the first page of this thread http://www.ogre3d.org/forums/viewtopic. ... 09#p454259.

Problem with D3D compiler they had back then shouldn't be a problem any more, as it's allowed from Windows 8.1 on.

Re: Windows8, WinRT, WOA & Metro

Posted: Fri Mar 07, 2014 11:41 pm
by KungFooMasta
False hope! Thanks for pointing it out though. I've found the locations in the code where I can make sure the D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY flag is used to compile the shader, but even when this flag is used I still get the error message. Here it is straight from the debugger:
Cannot assemble D3D11 high-level shader 50287ee7-fc53-9c1f-7a7c-ff2526c05377_FS Errors:
D:\Sandbox\SampleOgreApp\Debug\SampleOgreApp\AppX\Shader@0x08E73538(41,2-73): error X3017: 'FFP_Construct_Sampler_Wrapper': cannot implicitly convert from 'sampler2D' to 'TextureCube<float4>'
There should be a way to explicitly convert it, right?

It seems like we just need to add this function:

Code: Select all

void FFP_SampleTexture(in sampler2D s, 
               in float2 f,
               out float4 t)
{
   t = tex2D(s, f);
}
However now its complaining it doesn't know what sample2D is. I see in another part of this file, it looks like sample2D is not supported for D3D11:

Code: Select all

struct SamplerData2D 
	{ 
		#ifdef D3D11
			SamplerState	samplerState; 
			Texture2D		samplerObject;
		#else
			sampler2D		samplerObject;
		#endif
	};
I've tried modifying the function, for example taking a SamplerData2D object and using its samplerObject method, but I get other compiler errors. We just need a fully d3d11 compliant set of shaders and we'd be good. :cry:

Re: Windows8, WinRT, WOA & Metro

Posted: Sat Mar 08, 2014 1:07 am
by KungFooMasta
Ok I've been digging through this for a while now, its been slow at work for me so I have time to get this working. Unfortunately not successful. :lol:

I'd like to outline the problem, I think I know what it is, but not how to solve it.

SCENARIO: Trying to render ogrehead.mesh

ERROR:
Cannot assemble D3D11 high-level shader 50287ee7-fc53-9c1f-7a7c-ff2526c05377_FS Errors:
D:\Sandbox\SampleOgreApp\Debug\SampleOgreApp\AppX\Shader@0x08E73538(41,2-73): error X3017: 'FFP_Construct_Sampler_Wrapper': cannot implicitly convert from 'sampler2D' to 'TextureCube<float4>'
SOURCE:

Code: Select all

//-----------------------------------------------------------------------------
// Program Type: Fragment shader
// Language: hlsl
// Created by Ogre RT Shader Generator. All rights reserved.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//                         PROGRAM DEPENDENCIES
//-----------------------------------------------------------------------------
#include "FFPLib_Common.hlsl"
#include "FFPLib_Texturing.hlsl"

//-----------------------------------------------------------------------------
//                         GLOBAL PARAMETERS
//-----------------------------------------------------------------------------

sampler2D              gTextureSampler0 : register(s0);

//-----------------------------------------------------------------------------
// Function Name: main
// Function Desc: Pixel Program Entry point
//-----------------------------------------------------------------------------
void main
                (
                in float4 oPos_0 : SV_Position, 
                 in float4 iColor_0 : COLOR, 
                 in float2 iTexcoord2_0 : TEXCOORD0, 
                 out float4               oColor_0 : SV_Target
                )
{
                float4      lLocalParam_0;
                float4      texel_0;
                SamplerData2D      lLocalSamplerWrapper_2D;
                float4      source1;
                float4      source2;

                FFP_Construct(0.0, 0.0, 0.0, 0.0, lLocalParam_0);

                FFP_Assign(iColor_0, oColor_0);

------->      FFP_Construct_Sampler_Wrapper(gTextureSampler0, lLocalSamplerWrapper_2D);

                FFP_SampleTexture(lLocalSamplerWrapper_2D, iTexcoord2_0, texel_0);

                FFP_Assign(texel_0, source1);

                FFP_Assign(iColor_0, source2);

                FFP_Modulate(source1, source2, oColor_0);

                FFP_Add(oColor_0.xyz, lLocalParam_0.xyz, oColor_0.xyz);
}
FFPLib_Texturing.hlsl

Code: Select all

struct SamplerData2D 
	{ 
		#ifdef D3D11
			SamplerState	samplerState; 
			Texture2D		samplerObject;
		#else
			sampler2D		samplerObject;
		#endif
	};
...
	void FFP_Construct_Sampler_Wrapper(in Texture1D samplerObject,in SamplerState samplerState,out SamplerData1D samplerData)
	{
		samplerData.samplerObject = samplerObject;
		samplerData.samplerState = samplerState;
	}
	
	void FFP_Construct_Sampler_Wrapper(in Texture2D samplerObject,in SamplerState samplerState,out SamplerData2D samplerData)
	{
			samplerData.samplerObject = samplerObject;
			samplerData.samplerState = samplerState;
	}
	
	void FFP_Construct_Sampler_Wrapper(in Texture3D samplerObject,in SamplerState samplerState,out SamplerData3D samplerData)
	{
			samplerData.samplerObject = samplerObject;
			samplerData.samplerState = samplerState;
	}
	
	void FFP_Construct_Sampler_Wrapper(in TextureCube samplerObject,in SamplerState samplerState,out SamplerDataCube samplerData)
	{
			samplerData.samplerObject = samplerObject;
			samplerData.samplerState = samplerState;
	}
WHAT IS THE PROBLEM? There is no function that takes 2 parameters, an in parameter of sampler2D and an out parameter of SamplerData2D. What we need is this function:

Code: Select all

	void FFP_Construct_Sampler_Wrapper(in sampler2D samplerObject, out SamplerData2D samplerData)
	{
		// magical code that makes the generated shader code work correctly. Needs to convert the sampler2D to SamplerData2D object!!
	}
If anybody knows how to solve the problem that'd be great. I'm guessing most people must be using their own shaders or not using d3d11 and the FFP*.hlsl shaders, or they would have hit this issue.

Re: Windows8, WinRT, WOA & Metro

Posted: Wed Mar 12, 2014 1:12 am
by KungFooMasta
[UPDATE] Its working!! Here are the complete steps that will allow users to create a Windows Store App using Ogre.

BuildingOgreForWinRT.txt
1. Install TortoiseHG:

http://mercurial.selenic.com/downloads

Build Dependencies

2. Create a folder D:\Sandbox\OgreDependencies
3. From File Explorer, view this folder location, right click, TortoiseHG -> Clone...
4. Enter in "https://bitbucket.org/eugene_gff/ogre-d ... cies-winrt" and click "Clone"
5. Launch "D:\Sandbox\OgreDependencies\src\OgreDependencies.VS2013.WinRT.sln"
6. Select Build -> Batch Build... and click "Select All". Click "Build", everything should build successfully.
7. Libs should be placed under "D:\Sandbox\OgreDependencies\lib", for example "D:\Sandbox\OgreDependencies\lib\x86\Debug\FreeImaged.lib".

Build Ogre

8. Created a folder D:\Sandbox\Ogre. From file exporer, right click, TortoiseHG -> Clone...
9. Enter in "https://bitbucket.org/sinbad/ogre" and click "Clone"
10. Reading "BuildingOgreWinRT.txt"
11. Install CMake: http://www.cmake.org/files/v2.8/cmake-2 ... 32-x86.exe. I added CMAKE to system path.
12. Run CMAKE GUI. Set source code location to "D:/Sandbox/Ogre". Set binary output location to "D:/Sandbox/Ogre"
13. Press Configure. Select "Visual Studio 12" from the list.
14. Set OGRE_DEPENDENCIES_DIR to "D:\Sandbox\OgreDependencies" from Name/Value list. Press Configure. Make sure OGRE_STATIC and OGRE_BUILD_PLATFORM_WINRT are set. (checked) Keep pressing Configure until there are no rows outlined in red.
15. Press Generate.
16. Open up "D:\Sandbox\Ogre\OGRE.sln" in Visual Studio 2013
17. From the solution explorer, right click and remove the following projects: ALL_BUILD, INSTALL, PACKAGE
18. Right click OgreMain project and select "Retarget to 8.1". Select all other projects and hit OK.
19. Build the solution. 3 projects failed to build: OgreMain, OgreMeshLodGenerator, RenderSystem_Direct3D11
20. Right click RenderSystem_Direct3D11 project in solution explorer, open up properties. Configuration Properties -> C/C++ -> General -> Consume Windows Runtime Extension: Yes (/ZW)
21. In OgreMain project, open OgreErrorDIalogWinRT.cpp, and add "#include <iostream>" after the includes.
22. Right click OgreMeshLodGenerator project in solution explorer, open up properties. Configuration Properties -> C/C++ -> General -> SDL checks: No (/sdl-)
23. Batch build everything. Everything should be built! and the libs should be in "D:\Sandbox\Ogre\lib".

Issues?

1. You might need to add "D:\Sandbox\OgreDependencies\include" to the "Additional Include Directories" for the OgreMain and OgreOverlay projects. These paths can be specified in the project properties.
2. Make sure all projects are not using precompiled headers. Select all projects in the solution explorer,
Right click, than go to "Properties" select "Configuration Properties", than "All Configurations"
and under "Configuration Properties > C/C++ > Precompiled Headers > Precompiled Header" choose "Not Using Precompiled Headers".
BuildingOgreAppForWinRT.txt
Creating our Application

1. Launch Visual Studio 2013
2. File -> New Project...
3. Templates -> Visual C++ -> Store Apps -> Windows Apps -> DirectX App
4. Set name to "SampleOgreApp", location "D:\Sandbox", and check "Create directory for solution". Click OK.
5. Determine whether you will be building in Debug or Release mode. For now lets use Debug mode, and use Debug versions of the Ogre lib. Select "Debug" from the configuration drop down combobox.
6. In solution explorer, Right click SampleOgreApp project, properties. Make sure Configuration is set to "Debug" and Platform set to "Win32".
7. Configuration Properties -> C/C++ -> General -> Additional Include Directories. Add "D:\Sandbox\Ogre\include" and "D:\Sandbox\Ogre\Ogre\OgreMain\include"
8. Configuration Properties -> Linker -> General -> Additional Library Directories. Add "D:\Sandbox\Ogre\lib\Debug"
9. Configuration Properties -> Linker -> Input -> Additional Dependencies. Add OgreMainStatic_d.lib, FreeImaged.lib, freetype2311_d.lib, zlibd.lib, zziplibd.lib
10. In App.h add the following include:

#include "Ogre.h"

Make sure the project builds successfully. This will verify your lib paths and include paths
Make sure the project can run. Find the green arrow toolbar button and select "Simulator" from the drop down menu. Press then green Arrow button. At this point we have a rotating cube rendered using D3D.

Initializing Ogre

11. Replace App.h with the following code:

12. Replace App.cpp with the following code:

13. Add ShaderGeneratorTechniqueResolverListener.h to the project:

14. Configuration Properties -> C/C++ -> General -> Additional Include Directories. Add "D:\Sandbox\Ogre\Plugins\OctreeSceneManager\include", "D:\Sandbox\Ogre\RenderSystems\Direct3D11\include" and "D:\Sandbox\Ogre\Components\RTShaderSystem\include"
15. Configuration Properties -> Linker -> Input -> Additional Dependencies. Add Plugin_OctreeSceneManagerStatic_d.lib, RenderSystem_Direct3D11Static_d.lib, OgreRTShaderSystemStatic_d.lib, dxguid.lib
16. Add the following files to D:\Sandbox\SampleOgreApp\SampleOgreApp\Assets: ogrehead.mesh, ogre.material, greenskin.jpg, tusk.jpg, spheremap.png
17. Add the files from step 15 to the project by right clicking on the "Assets" folder (filter) in the Solution Explorer, Add -> Existing Item...
18. Copy the following hlsl files to your project (D:\Sandbox\SampleOgreApp\SampleOgreApp\Assets) and add them to the "Assets" folder in the Solution Explorer: FFPLib_Common.hlsl, FFPLib_Fog.hlsl, FFPLib_Lighting.hlsl, FFPLib_Texturing.hlsl, FFPLib_Transform.hlsl
19. Make sure to explicitly right click and set properties for all hlsl files, setting Content=yes and "Do not participate in build". (By default they are recognized)
20. The currently provided hlsl files (step 18) will not compile correctly as seen when trying to use FFPLib_Texturing.hlsl. Fix TBD

Make sure the project builds successfully.
Make sure the project can run.

Issues?
1. Check Ogre.log. Everybody's path will use a different app GUID, here is mine: C:\Users\bkinsey\AppData\Local\Packages\856f2e6b-4a1a-4e76-9b56-535eee39bd3a_4bzmt7j5bjbb6\LocalState
App.h

Code: Select all

#pragma once

#include "pch.h"

#include "Ogre.h"
#include "OgreD3D11Plugin.h"
#include "OgreOctreePlugin.h"
#include "OgreRTShaderSystem.h"

#include "ShaderGeneratorTechniqueResolverListener.h"

#include <string>

namespace SampleOgreApp
{
	// Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events.
	ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView
	{
	public:
		App();
		virtual ~App();

		// IFrameworkView Methods.
		virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
		virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
		virtual void Load(Platform::String^ entryPoint);
		virtual void Run();
		virtual void Uninitialize();

	protected:
		// Application lifecycle event handlers.
		void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
		void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
		void OnResuming(Platform::Object^ sender, Platform::Object^ args);

		// Window event handlers.
		void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
		void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
		void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);

		// DisplayInformation event handlers.
		void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
		void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
		void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);

	private:
		bool m_windowClosed;
		bool m_windowVisible;

		Ogre::Root* mOgreRoot;
		Ogre::RenderWindow* mOgreRenderWindow;

		Ogre::D3D11Plugin* mD3D11Plugin;
		Ogre::OctreePlugin* mOctreePlugin;

		Ogre::RTShader::ShaderGenerator* mShaderGenerator;                       // The Shader generator instance.
		ShaderGeneratorTechniqueResolverListener* mMaterialMgrListener;          // Shader generator material manager listener.

		void CreateShadersForDefaultMaterialsUsingRTSS();

		std::string ConvertPlatformStringToSTDString(Platform::String^ s);
		Platform::String^ ConvertSTDStringToPlatformString(const std::string& s);
	};
}

ref class Direct3DApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
{
public:
	virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
};
App.cpp

Code: Select all

#include "pch.h"
#include "App.h"

#include <ppltasks.h>

using namespace SampleOgreApp;

using namespace concurrency;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;

// The main function is only used to initialize our IFrameworkView class.
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
	auto direct3DApplicationSource = ref new Direct3DApplicationSource();
	CoreApplication::Run(direct3DApplicationSource);
	return 0;
}

IFrameworkView^ Direct3DApplicationSource::CreateView()
{
	return ref new App();
}

App::App() :
	m_windowClosed(false),
	m_windowVisible(true),
	mOgreRoot(nullptr)
{
}

App::~App()
{
	delete mOgreRoot;
}

std::string App::ConvertPlatformStringToSTDString(Platform::String^ s)
{
	// need to convert to narrow (OEM or ANSI) codepage so that fstream can use it 
	// properly on international systems.
	char npath[MAX_PATH];

	// Runtime is modern, narrow calls are widened inside CRT using CP_ACP codepage.
	UINT codepage = CP_ACP;

	if (0 == WideCharToMultiByte(codepage, 0 /* Use default flags */, s->Data(), -1, npath, sizeof(npath), NULL, NULL))
	{
		throw ref new Platform::FailureException("Unable to convert Platform string to std::string!");
	}

	// success
	return std::string(npath);
}

Platform::String^ App::ConvertSTDStringToPlatformString(const std::string& s)
{
	std::vector<wchar_t> wpath(s.length() + 1, '\0');

	// Runtime is modern, narrow calls are widened inside CRT using CP_ACP codepage.
	UINT codepage = CP_ACP;

	(void)MultiByteToWideChar(codepage, 0, s.data(), s.length(), &wpath[0], wpath.size());

	return ref new Platform::String(&wpath[0]);
}

void App::CreateShadersForDefaultMaterialsUsingRTSS()
{
	// creates shaders for base material BaseWhite using the RTSS
	Ogre::MaterialPtr baseWhite = Ogre::MaterialManager::getSingleton().getByName("BaseWhite", Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
	baseWhite->setLightingEnabled(false);
	mShaderGenerator->createShaderBasedTechnique(
		"BaseWhite",
		Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
		Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
	mShaderGenerator->validateMaterial(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME,
		"BaseWhite");
	if (baseWhite->getNumTechniques() > 1)
	{
		baseWhite->getTechnique(0)->getPass(0)->setVertexProgram(
			baseWhite->getTechnique(1)->getPass(0)->getVertexProgram()->getName());
		baseWhite->getTechnique(0)->getPass(0)->setFragmentProgram(
			baseWhite->getTechnique(1)->getPass(0)->getFragmentProgram()->getName());
	}

	// creates shaders for base material BaseWhiteNoLighting using the RTSS
	mShaderGenerator->createShaderBasedTechnique(
		"BaseWhiteNoLighting",
		Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
		Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
	mShaderGenerator->validateMaterial(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME,
		"BaseWhiteNoLighting");
	Ogre::MaterialPtr baseWhiteNoLighting = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting", Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
	if (baseWhite->getNumTechniques() > 1)
	{
		baseWhiteNoLighting->getTechnique(0)->getPass(0)->setVertexProgram(
			baseWhiteNoLighting->getTechnique(1)->getPass(0)->getVertexProgram()->getName());
		baseWhiteNoLighting->getTechnique(0)->getPass(0)->setFragmentProgram(
			baseWhiteNoLighting->getTechnique(1)->getPass(0)->getFragmentProgram()->getName());
	}
}

// The first method called when the IFrameworkView is being created.
void App::Initialize(CoreApplicationView^ applicationView)
{
	// Register event handlers for app lifecycle. This example includes Activated, so that we
	// can make the CoreWindow active and start rendering on the window.
	applicationView->Activated +=
		ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);

	CoreApplication::Suspending +=
		ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);

	CoreApplication::Resuming +=
		ref new EventHandler<Platform::Object^>(this, &App::OnResuming);
}

// Called when the CoreWindow object is created (or re-created).
void App::SetWindow(CoreWindow^ window)
{
	window->SizeChanged += 
		ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);

	window->VisibilityChanged +=
		ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);

	window->Closed += 
		ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);

	DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();

	currentDisplayInformation->DpiChanged +=
		ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged);

	currentDisplayInformation->OrientationChanged +=
		ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged);

	DisplayInformation::DisplayContentsInvalidated +=
		ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated);

	// Disable all pointer visual feedback for better performance when touching.
	auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
	pointerVisualizationSettings->IsContactFeedbackEnabled = false; 
	pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;

	// OGRE INTIALIZATION - I've decided to do this here because we need a CoreWindow handle in order to create the Ogre::RenderWindow object.

	if (mOgreRoot == nullptr)
	{

		// The Ogre Root constructor requires 3 directory paths: Plugin path, config path, log path
		//	1. We don't want to have any dll's and have all the libs build staticly, so we can tell Ogre not to look for any plugins by supply a blank string.
		//	2. Similarly, we won't be using an Ogre.cfg file, so we pass in a blank string.
		//  3. We do want logs produced by Ogre, in case there are some issues that need investigation.  For this we'll create a file and pass its path to Ogre.

		Ogre::String emptyString = Ogre::BLANKSTRING;

		// Since we are using the CreateFileAsync method, and we need to make sure the file exists before we instantiate Ogre::Root, we have to use the .then functionality 
		// to make the operations go in order
		Windows::Storage::StorageFolder^ rootApplicationDataFolder = Windows::Storage::ApplicationData::Current->LocalFolder;

		auto createFileTask = create_task(rootApplicationDataFolder->CreateFileAsync(ConvertSTDStringToPlatformString("Ogre.log"), Windows::Storage::CreationCollisionOption::GenerateUniqueName));
		createFileTask.then([=](Windows::Storage::StorageFile^ ogreLog)
		{
			mOgreRoot = new Ogre::Root(emptyString, emptyString, ConvertPlatformStringToSTDString(ogreLog->Path));

			// Let's continue initializing Ogre here, right after instantiating Ogre::Root

			mD3D11Plugin = OGRE_NEW Ogre::D3D11Plugin();
			mOgreRoot->installPlugin(mD3D11Plugin);

			mOctreePlugin = OGRE_NEW Ogre::OctreePlugin();
			mOgreRoot->installPlugin(mOctreePlugin);

			// Lets set the Render System for Ogre to use. (The D3D11Plugin we just loaded)
			mOgreRoot->setRenderSystem(mOgreRoot->getAvailableRenderers()[0]);

			// Initialize Ogre! (NOTE: We cannot create a Render Window until we have a handle to the CoreWindow of our WinRT app)
			mOgreRoot->initialise(false, "OGRE Sample Browser");
						
			// Create our RenderWindow
			Ogre::NameValuePairList miscParams;
			if (window != nullptr)
			{
				miscParams["externalWindowHandle"] = Ogre::StringConverter::toString((size_t)reinterpret_cast<void*>(window));
				mOgreRenderWindow = mOgreRoot->createRenderWindow("SampleOgreApp RenderWindow", static_cast<unsigned int>(window->Bounds.Width), static_cast<unsigned int>(window->Bounds.Height), false, &miscParams);
				
				// With the creation of the RenderWindow, the Material manager is initialized.  If you want materials to be parsed, they need to first be declared using Resource Groups.

				// In this example we want to display an ogre head, which is made of a mesh, material, and textures. Lets tell Ogre to locate these resources for us and associate
				// them with the default Resource Group.  We can do this via the addResourceLocation API.

				// Remember that all assets should be added to the project from inside Visual Studio, in the solution explorer.
				// The location of each asset is defined by its "Relative Path", which can be viewed in the Property window with the asset file selected. (View -> Properties Window)
				// NOTE: Adding filters (folders) to the project and having files in these folders does not indicate their relative path.
				// NOTE: Make sure each file has Content=true for its properties, otherwise it won't be packaged with the application.

				// All of the resources required for the ogre head are stored in our Assets folder. (D:\Sandbox\SampleOgreApp\SampleOgreApp\Assets)
				// Lets add the relative path to the default resource group.
				Ogre::ResourceGroupManager::getSingleton().addResourceLocation(".\\Assets\\", "FileSystem", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

				// Now that we have declared all resource locations we care about, we can initialize our ResourceGroups, and which will parse any scripts such as Materials and programs.
				Ogre::ResourceGroupManager::getSingletonPtr()->initialiseAllResourceGroups();
				
				// The RTShader system needs to be used for rendering, since the D3D11 device does not have a fixed function pipeline.
				// Initialization of the RTShader must be called after the RenderWindow is created, as the D3D11 RenderSystem creates the D3D11GpuProgramManager at this time.
				Ogre::RTShader::ShaderGenerator::initialize();
				mShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr();
				mShaderGenerator->setTargetLanguage("hlsl", 4.0f);
				
				// By providing the ShaderGenerator with a Cache path, we can re-use shaders. If the required shaders do not exist, they will be built and placed in the cache for future use.
				// If no Cache is specified, the shaders will be built every time they are needed, and stored in a temporary system path.  A good practice would be to set the cache
				// during development, and for submission, bundle the necessary shaders with with the project.
				mShaderGenerator->setShaderCachePath(ConvertPlatformStringToSTDString(rootApplicationDataFolder->Path));

				// Create and register the material manager listener if it doesn't exist yet.
				ShaderGeneratorTechniqueResolverListener* mMaterialMgrListener = new ShaderGeneratorTechniqueResolverListener(mShaderGenerator);
				Ogre::MaterialManager::getSingleton().addListener(mMaterialMgrListener);

				// Create a dummy Scene

				// Re-using code from Ogre tutorial: http://www.ogre3d.org/tikiwiki/tiki-index.php?page=Basic+Tutorial+1&structure=Tutorials
				// and from ExampleApplication.h

				Ogre::SceneManager* sm = mOgreRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE, "DummyScene");
				sm->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));

				// Add the SceneManager to the ShaderGenerator so that it can listen for Scene rendering events and configure gpu parameters
				mShaderGenerator->addSceneManager(sm);

				CreateShadersForDefaultMaterialsUsingRTSS();
				
				Ogre::Camera* cam = sm->createCamera("DummyCam");
				// Position it at 500 in Z direction
				cam->setPosition(Ogre::Vector3(0, 0, 500));
				// Look back along -Z
				cam->lookAt(Ogre::Vector3(0, 0, -300));
				cam->setNearClipDistance(5);
				
				Ogre::Viewport* vp = mOgreRenderWindow->addViewport(cam);

				Ogre::Entity* ogreHead = sm->createEntity("Head", "ogrehead.mesh");
				Ogre::SceneNode* headNode = sm->getRootSceneNode()->createChildSceneNode("HeadNode");
				headNode->attachObject(ogreHead);

				Ogre::Light* light = sm->createLight("MainLight");
				light->setPosition(20, 80, 50);
			}
		});
	}
}

// Initializes scene resources, or loads a previously saved app state.
void App::Load(Platform::String^ entryPoint)
{
}

// This method is called after the window becomes active.
void App::Run()
{
	// Let's wait until Ogre has been initialized..
	while (mOgreRoot == nullptr)
		CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);

	while (!m_windowClosed)
	{
		if (m_windowVisible)
		{
			CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
			
			// Perform game-logic update

			// Render
			mOgreRoot->renderOneFrame();
		}
		else
		{
			CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
		}
	}
}

// Required for IFrameworkView.
// Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
// class is torn down while the app is in the foreground.
void App::Uninitialize()
{
}

// Application lifecycle event handlers.

void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
	// Run() won't start until the CoreWindow is activated.
	CoreWindow::GetForCurrentThread()->Activate();
}

void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
	// Save app state asynchronously after requesting a deferral. Holding a deferral
	// indicates that the application is busy performing suspending operations. Be
	// aware that a deferral may not be held indefinitely. After about five seconds,
	// the app will be forced to exit.
	SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();

	create_task([this, deferral]()
	{
		// Insert your code here.

		deferral->Complete();
	});
}

void App::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
	// Restore any data or state that was unloaded on suspend. By default, data
	// and state are persisted when resuming from suspend. Note that this event
	// does not occur if the app was previously terminated.

	// Insert your code here.
}

// Window event handlers.

void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
{
}

void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
	m_windowVisible = args->Visible;
}

void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
	m_windowClosed = true;
}

// DisplayInformation event handlers.

void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
{
}

void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
{
}

void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args)
{
}
ShaderGeneratorTechniqueResolverListener.h

Code: Select all

#include "Ogre.h"
#include "OgreRTShaderSystem.h"

/** This class demonstrates basic usage of the RTShader system.
It sub class the material manager listener class and when a target scheme callback
is invoked with the shader generator scheme it tries to create an equivalent shader
based technique based on the default technique of the given material.
*/
class ShaderGeneratorTechniqueResolverListener : public Ogre::MaterialManager::Listener
{
public:

	ShaderGeneratorTechniqueResolverListener(Ogre::RTShader::ShaderGenerator* pShaderGenerator)
	{
		mShaderGenerator = pShaderGenerator;
	}

	/** This is the hook point where shader based technique will be created.
	It will be called whenever the material manager won't find appropriate technique
	that satisfy the target scheme name. If the scheme name is out target RT Shader System
	scheme name we will try to create shader generated technique for it.
	*/
	virtual Ogre::Technique* handleSchemeNotFound(unsigned short schemeIndex,
		const Ogre::String& schemeName, Ogre::Material* originalMaterial, unsigned short lodIndex,
		const Ogre::Renderable* rend)
	{
		Ogre::Technique* generatedTech = NULL;

		// Case this is the default shader generator scheme.
		if (schemeName == Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME)
		{
			bool techniqueCreated;

			// Create shader generated technique for this material.
			techniqueCreated = mShaderGenerator->createShaderBasedTechnique(
				originalMaterial->getName(),
				Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
				schemeName);

			// Case technique registration succeeded.
			if (techniqueCreated)
			{
				// Force creating the shaders for the generated technique.
				mShaderGenerator->validateMaterial(schemeName, originalMaterial->getName());

				// Grab the generated technique.
				Ogre::Material::TechniqueIterator itTech = originalMaterial->getTechniqueIterator();

				while (itTech.hasMoreElements())
				{
					Ogre::Technique* curTech = itTech.getNext();

					if (curTech->getSchemeName() == schemeName)
					{
						generatedTech = curTech;
						break;
					}
				}
			}
		}

		return generatedTech;
	}

protected:
	Ogre::RTShader::ShaderGenerator*        mShaderGenerator;                       // The shader generator instance.
};
App.cpp has a lot of comments in it, I think it would be beneficial for people reading through the code.

Enjoy!

Re: Windows8, WinRT, WOA & Metro

Posted: Sun Mar 16, 2014 6:30 pm
by Borrillis
@KungfooMasta

You need to add

Code: Select all

mShaderGenerator->setTargetLanguage("hlsl", 4.0f);
after you initialize the ShaderGenerator. This will force it to emit the proper types for the shader parameters, and not use sample2D.

Your writeup is also missing a few things, I'll post an update here after I gather them all together. But thanks for the effort you put into this, this is very cool to have a working instance of OGRE for Windows Store Apps.

**UPDATE**
Configuring Ogre:
Make sure you select OGRE_STATIC, and OGRE_BUILD_PLATFORM_WINRT

Re: Windows8, WinRT, WOA & Metro

Posted: Mon Mar 17, 2014 8:17 pm
by KungFooMasta
WOW! I cannot believe that one line of code was all I needed. You are a life saver man!! Many thanks, now I see a green ogre head, very exciting. :)

I have updated the steps above with your feedback.

Re: Windows8, WinRT, WOA & Metro

Posted: Tue Mar 25, 2014 1:49 am
by Jake007
Hi!

Excellent work!
I continued work from code KungFooMasta provided and managed to tweak evertything a bit to sucsessfully pass certification :-).
I'll post required changes in the next few days.

Re: Windows8, WinRT, WOA & Metro

Posted: Tue Mar 25, 2014 8:26 pm
by Borrillis
Jake007 wrote:Hi!

Excellent work!
I continued work from code KungFooMasta provided and managed to tweak evertything a bit to sucsessfully pass certification :-).
I'll post required changes in the next few days.
That's awesome, please post a link to your game once it's available. I would love to hear what you had to do to pass certification. I have done a complete detailed write-up on my blog of the results of what I had been able to do, and everything I picked up from this thread. It's posted here : http://michaelcummings.net/mathoms/gett ... indows-8.1
I'll update it for anything that you have in addition, which would include a small blurb about your game and a link to it, if you'd be willing.

Re: Windows8, WinRT, WOA & Metro

Posted: Thu Mar 27, 2014 7:05 pm
by KungFooMasta
!! Also interested in what changes need to be made for certification, as I didn't try to push my bare bones app to marketplace. Thanks for sharing!

Re: Windows8, WinRT, WOA & Metro

Posted: Fri Mar 28, 2014 1:23 am
by Jake007
@KungFooMasta
I pushed you app to the store with note for the testers that it's only certification test. Reply was that code would pass, but there were other things that didn't (tile images ugly as hell, description etc.).

Note: I do not fully understand what kind of consequences step #1 might have (couldn't find anything in the docs). It just works :D!

Code: Select all

1. Edit src\RenderSystems\Direct3D11\include\OgreD3D11Prerequisites.h, line 96 from IDXGIDevice2 to IDXGIDevice3.
2. In project properties make sure Safe Exception Handlers are on (Project properties -> Linker -> Advanced -> Image Has Safe Exception Handlers : Yes (/SAFESEH))
3. App must be compiled as Release.
4. derive D3D11Plugin and add trim function (code below)
5. Replace D3D11Plugin with D3D11RTRenderer (App.h line 56, App.cpp line 177)
6. Call trim function in OnSuspending Event (App.cpp, line 306) (mD3D11Plugin->trim() )

Code: Select all

#pragma once
#include "O:\src\RenderSystems\Direct3D11\include\OgreD3D11Plugin.h"

using namespace Ogre;

class D3D11RTRenderer :
	public D3D11Plugin
{
	public:
	D3D11RTRenderer();
	~D3D11RTRenderer();

	void trim()
	{
		auto device = mRenderSystem->_getDevice();
		IDXGIDeviceN * pDXGIDevice;
		device->QueryInterface(__uuidof(IDXGIDeviceN), (void **) &pDXGIDevice);
		pDXGIDevice->Trim();
	}
};
Note: D3D11RTRenderer code isn't exemplary but it should suffice.

I believe that is everything.

@Borrillis
Nice blog post :)! Unfortunately didn't have time to port any existing app but I hope I'll be able soon.

While reading through it made me think how many thing must be done and how time consuming it is to setup a workplace.
I'll post VS Project template in an upcoming week if there is anyone interested. Or perhaps Nuget packages would be better?

Re: Windows8, WinRT, WOA & Metro

Posted: Fri Mar 28, 2014 11:37 pm
by KungFooMasta
Awesome! I'll have to remember these steps when I go to certify, it could be a while. :)

Another question, but not closely related. Do you know how to convert between a C++/CX (Visual C++) pointer and a native C++ pointer? I am wrapping Ogre with classes that can be used across the ABI, for example I have a SceneNode class, and I want to store a pointer to my wrapper class using Ogre::SceneNode::SetUserAny.

Can't find a way to convert SceneNode^ to SceneNode*. The Ogre::any_cast doesn't seem to work with Visual C++ pointers. (^ vs *)

Some sample code for reference:

Code: Select all

mySceneNode->getUserObjectBindings().setUserAny(Ogre::Any(this));

Ogre::Any any = mySceneNode->getUserObjectBindings().getUserAny();
OgreWinRTWrapper::SceneNode^ temp = Ogre::any_cast<OgreWinRTWrapper::SceneNode^>(any);
Doesn't compile.

Re: Windows8, WinRT, WOA & Metro

Posted: Mon Mar 31, 2014 7:52 pm
by KungFooMasta
haven't tested this but I think this is the answer:

Code: Select all

		// Let's store a pointer to this SceneNode wrapper instance in the Ogre::SceneNode instance.
		sn->getUserObjectBindings().setUserAny(Ogre::Any(reinterpret_cast<void*>(this)));

		// Retrieving a pointer to this SceneNode wrapper instance
		Ogre::Any any = sn->getUserObjectBindings().getUserAny();

		void* nativePtr = Ogre::any_cast<void*>(any);
		SceneNode^ temp = reinterpret_cast<OgreWinRTWrapper::SceneNode^>(nativePtr);