public static bool GetOrGenerate(string sourceFileName, bool forceUpdate, int specifiedSize, out string envFileName, out string irrFileName, out string error) { EngineThreading.CheckMainThread(); var destFileNameBase = GetDestFileNameBase(sourceFileName); GetDestFileNames(destFileNameBase, out var infoFileName, out envFileName, out irrFileName); if (!GetInfoFromSourceFile(sourceFileName, out var sourceFileHash, out var sourceFileSize)) { error = "Unable to get hash from source file."; return(false); } ReadCachedInfoFile(destFileNameBase, out var cacheSourceFileHash, out var cacheSourceFileSize); //, out var cacheSourceFileFormat ); bool needUpdate = sourceFileHash != cacheSourceFileHash || sourceFileSize != cacheSourceFileSize; if (needUpdate || forceUpdate) { return(Generate(sourceFileName, sourceFileHash, sourceFileSize, specifiedSize, out error)); } error = ""; return(true); }
/// <summary> /// Adds a viewport to the rendering target. /// </summary> /// <param name="insertIndex"> /// The relative order of the viewport with others on the target (allows overlapping /// viewports i.e. picture-in-picture). /// </param> /// <returns>The viewport.</returns> /// <remarks> /// A viewport is the rectangle into which redering output is sent. This method adds /// a viewport to the render target, rendering from the supplied camera. The /// rest of the parameters are only required if you wish to add more than one viewport /// to a single rendering target. Note that size information passed to this method is /// passed as a parametric, i.e. it is relative rather than absolute. This is to allow /// viewports to automatically resize along with the target. /// </remarks> public Viewport AddViewport(bool createSimple3DRenderer, bool createCanvasRenderer, int insertIndex = 100000) { EngineThreading.CheckMainThread(); //!!!!!!как указывать rendering pipeline? unsafe { //OgreViewport* realViewport = (OgreViewport*)OgreRenderTarget.addViewport( realObject, insertIndex ); Viewport viewport = new Viewport(); // realViewport ); viewport.parent = this; //viewport.UpdateNativeBackgroundColor(); if (insertIndex >= viewports.Count) { viewports.Add(viewport); } else { viewports.Insert(insertIndex, viewport); } viewport.OnAdd(createSimple3DRenderer, createCanvasRenderer); return(viewport); } }
unsafe static bool find(string pattern, bool recursive, bool dirs, void *userData) { //!!!!!right? EngineThreading.CheckMainThread(); try { string[] names; if (dirs) { //!!!!! names = VirtualDirectory.GetDirectories("", pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } else { //!!!!! names = VirtualDirectory.GetFiles("", pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } foreach (string name in names) { findAddItem(RenderingSystem.realRoot, name, userData); } } catch { return(false); } return(true); }
public void WindowMovedOrResized(Vector2I size) // bool fullScreen )//, Vec2I windowSize ) { if (Disposed) { return; } EngineThreading.CheckMainThread(); this.size = size; //!!!!по идее не во всех графических API надо пересоздавать if (thisIsApplicationWindow) { Bgfx.Reset(size.X, size.Y, RenderingSystem.GetApplicationWindowResetFlags()); } else { frameBuffer.Dispose(); frameBuffer = new FrameBuffer(windowHandle, size.X, size.Y); } //update aspect ratio foreach (Viewport viewport in viewports) { viewport.UpdateAspectRatio(); } }
public static RenderWindow CreateRenderWindow(IntPtr parentWindowHandle, Vector2I size) { EngineThreading.CheckMainThread(); var frameBuffer = new FrameBuffer(parentWindowHandle, size.X, size.Y); var renderWindow = new RenderWindow(frameBuffer, size, parentWindowHandle, false); return(renderWindow); }
static bool fileExists(string fileName) { //!!!!!right? EngineThreading.CheckMainThread(); ////watermark //if( fileName == WmImage.GetName() ) // return true; return(VirtualFile.Exists(fileName)); }
//!!!!!!! public static bool RestoreDeviceAfterLost() { EngineThreading.CheckMainThread(); //!!!! return(true); //unsafe //{ // return OgreRenderSystem.restoreDeviceAfterLost( RendererWorld.realRoot ); //} }
internal IDisposable GetNativeObject() { if (Disposed) { Log.Fatal("GpuVertexBuffer: GetNativeObject: Disposed."); } EngineThreading.CheckMainThread(); if (Flags.HasFlag(GpuBufferFlags.Dynamic) || Flags.HasFlag(GpuBufferFlags.ComputeWrite)) { ////delete old static when changed to dynamic //if( realObject != null && realObject is SharpBgfx.VertexBuffer ) //{ // realObject.Dispose(); // realObject = null; //} if (realObject == null) { var nativeFlags = SharpBgfx.BufferFlags.ComputeRead; // | SharpBgfx.BufferFlags.ComputeTypeFloat; if (Flags.HasFlag(GpuBufferFlags.ComputeWrite)) { nativeFlags |= SharpBgfx.BufferFlags.ComputeWrite; } realObject = new SharpBgfx.DynamicVertexBuffer(vertexCount, vertexDeclaration, nativeFlags); dynamic_needUpdateNative = true; } if (!Flags.HasFlag(GpuBufferFlags.ComputeWrite)) { if (dynamic_needUpdateNative) { dynamic_needUpdateNative = false; var buffer = (SharpBgfx.DynamicVertexBuffer)realObject; var memory = RendererMemoryUtility.AllocateAutoReleaseMemoryBlock(new ArraySegment <byte>(vertices, 0, vertexCountActual * vertexSize)); buffer.Update(0, memory); } } } else { if (realObject == null) { var memory = RendererMemoryUtility.AllocateAutoReleaseMemoryBlock(vertices); realObject = new SharpBgfx.VertexBuffer(memory, vertexDeclaration, SharpBgfx.BufferFlags.ComputeRead /* | SharpBgfx.BufferFlags.ComputeTypeFloat*/); } } return(realObject); }
//!!!!!!! /// <summary> /// D3D specific method to return whether the device has been lost. /// </summary> public static bool IsDeviceLostByTestCooperativeLevel() { //!!!!!! EngineThreading.CheckMainThread(); //!!!! return(false); //unsafe //{ // return OgreRenderSystem.isDeviceLostByTestCooperativeLevel( RendererWorld.realRoot ); //} }
public void WindowMovedOrResized(Vector2I size) // bool fullScreen )//, Vec2I windowSize ) { if (Disposed) { return; } EngineThreading.CheckMainThread(); //unsafe //{ //!!!!было //MyOgreSceneManager.destroyShadowTextures( SceneManager.realObject ); //!!!!как теперь? текстуры композитинга удалять? где еще? //MyOgreSceneManager.destroyAdditionalMRTs( SceneManager.realObject ); //} //foreach( Viewport viewport in viewports ) //{ // foreach( CompositorInstance instance in viewport.CompositorInstances ) // instance.DoRealEnabledUpdate( false ); //} this.size = size; //!!!!по идее не во всех графических API надо пересоздавать if (thisIsApplicationWindow) { Bgfx.Reset(size.X, size.Y, RenderingSystem.GetApplicationWindowResetFlags()); } else { frameBuffer.Dispose(); frameBuffer = new FrameBuffer(windowHandle, size.X, size.Y); } //unsafe //{ // OgreRenderWindow.windowMovedOrResized( realObjectRenderWindow, fullScreen );//, windowSize.X, windowSize.Y ); //} //GetSizeFromNative(); //update aspect ratio foreach (Viewport viewport in viewports) { viewport.UpdateAspectRatio(); } }
unsafe static int read(void */*MyOgreVirtualDataStream*/ stream, void *buf, int count) { //!!!!!right? EngineThreading.CheckMainThread(); //BeginCounter(); //VirtualFileStream s = GetStreamByOgreStream( stream ); //int result = s.ReadUnmanaged( (IntPtr)buf, count ); //EndCounter(); //return result; VirtualFileStream s = GetStreamByOgreStream(stream); return(s.ReadUnmanaged((IntPtr)buf, count)); }
///// <summary> ///// D3D specific method to return whether the device has been lost. ///// </summary> internal static bool IsDeviceLost() { //!!!!!! EngineThreading.CheckMainThread(); //!!!! return(false); //unsafe //{ // if( OgreRenderSystem.isDeviceLost( RendererWorld.realRoot ) ) // return true; // if( IsDeviceLostByTestCooperativeLevel() ) // return true; // return false; //} }
protected override void OnDispose() { if (realObject != null) { //after shutdown check if (RenderingSystem.Disposed) { //waiting for .NET Standard 2.0 Log.Fatal("Renderer: Dispose after Shutdown."); //Log.Fatal( "Renderer: Dispose after Shutdown: {0}()", System.Reflection.MethodInfo.GetCurrentMethod().Name ); } EngineThreading.ExecuteFromMainThreadLater(delegate(IDisposable obj) { obj.Dispose(); }, realObject); realObject = null; } lock (GpuBufferManager.vertexBuffers) GpuBufferManager.vertexBuffers.Remove(this); //base.OnDispose(); }
//static double totalTime; //static double startTime; //static int openings; //static int calls; //static void BeginCounter() //{ // //xx xx; // startTime = RendererWorld.renderTimerManager.GetSystemTime(); // calls++; //} //static void EndCounter() //{ // double t = RendererWorld.renderTimerManager.GetSystemTime() - startTime; // totalTime += t; //} unsafe static bool open(void */*MyOgreVirtualDataStream*/ stream, string fileName, ref int streamSize, ref bool fileNotFound) { //!!!!!right? EngineThreading.CheckMainThread(); //!!!!!посмотреть, что тут грузится. по сути не надо это ведь совсем. ну для шейдеров разве чтоли. тогда будет ли работать с мультипотоке? //openings++; //Log.Info( "OPEN: " + fileName ); streamSize = 0; fileNotFound = false; VirtualFileStream s; try { //watermark //if( fileName == WmImage.GetName() ) // s = WmImage.Open(); //else s = VirtualFile.Open(fileName); } catch (FileNotFoundException) { fileNotFound = true; return(false); } catch { return(false); } streamSize = (int)s.Length; openedStreams.Add((IntPtr)stream, s); lastOpenedOgreStream = (MyOgreVirtualDataStream *)stream; lastOpenedStream = s; return(true); }
unsafe static bool findFileInfo(string pattern, bool recursive, bool dirs, void *userData) { //!!!!!right? EngineThreading.CheckMainThread(); try { if (dirs) { //!!!!! string[] names = VirtualDirectory.GetDirectories("", pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); foreach (string name in names) { findFileInfoAddItem(RenderingSystem.realRoot, name, Path.GetDirectoryName(name).Replace('\\', '/') + "/", Path.GetFileName(name), 0, 0, userData); } } else { string[] names = VirtualDirectory.GetFiles("", pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); foreach (string name in names) { int length = (int)VirtualFile.GetLength(name); findFileInfoAddItem(RenderingSystem.realRoot, name, Path.GetDirectoryName(name).Replace('\\', '/') + "/", Path.GetFileName(name), length, length, userData); } } } catch { return(false); } return(true); }
public static MultiRenderTarget CreateMultiRenderTarget(MultiRenderTarget.Item[] items) { //!!!! EngineThreading.CheckMainThread(); Attachment[] attachments = new Attachment[items.Length]; for (int n = 0; n < attachments.Length; n++) { var item = items[n]; var attachment = new Attachment(); attachment.Texture = item.texture.Result.RealObject; attachment.Mip = item.mip; attachment.Layer = item.layer; attachment.Access = ComputeBufferAccess.Write; attachments[n] = attachment; } var frameBuffer = new FrameBuffer(attachments); var mrt = new MultiRenderTarget(frameBuffer, items); return(mrt); }
internal IDisposable GetNativeObject() { if (Disposed) { Log.Fatal("GpuIndexBuffer: GetNativeObject: Disposed."); } EngineThreading.CheckMainThread(); if (Flags.HasFlag(GpuBufferFlags.Dynamic) || Flags.HasFlag(GpuBufferFlags.ComputeWrite)) { ////delete old static when changed to dynamic //if( realObject != null && realObject is SharpBgfx.IndexBuffer ) //{ // realObject.Dispose(); // realObject = null; //} if (realObject == null) { var nativeFlags = SharpBgfx.BufferFlags.Index32 | SharpBgfx.BufferFlags.ComputeRead; // | SharpBgfx.BufferFlags.ComputeTypeFloat; if (Flags.HasFlag(GpuBufferFlags.ComputeWrite)) { nativeFlags |= SharpBgfx.BufferFlags.ComputeWrite; } //dynamic buffers are always 32-bit realObject = new SharpBgfx.DynamicIndexBuffer(indices.Length, nativeFlags); dynamic_needUpdateNative = true; realObject16Bit = false; } if (!Flags.HasFlag(GpuBufferFlags.ComputeWrite)) { if (dynamic_needUpdateNative) { dynamic_needUpdateNative = false; var buffer = (SharpBgfx.DynamicIndexBuffer)realObject; var memory = RendererMemoryUtility.AllocateAutoReleaseMemoryBlock(new ArraySegment <int>(indices, 0, indexCountActual)); buffer.Update(0, memory); } } } else { if (realObject == null) { bool use16Bit = true; foreach (var index in indices) { if (index > 65535) { use16Bit = false; break; } } if (use16Bit) { var indices16 = new ushort[indices.Length]; for (int n = 0; n < indices16.Length; n++) { indices16[n] = (ushort)indices[n]; } var memory = RendererMemoryUtility.AllocateAutoReleaseMemoryBlock(indices16); realObject = new SharpBgfx.IndexBuffer(memory, SharpBgfx.BufferFlags.ComputeRead /* | SharpBgfx.BufferFlags.ComputeTypeFloat*/); } else { var memory = RendererMemoryUtility.AllocateAutoReleaseMemoryBlock(indices); realObject = new SharpBgfx.IndexBuffer(memory, SharpBgfx.BufferFlags.Index32 | SharpBgfx.BufferFlags.ComputeRead /* | SharpBgfx.BufferFlags.ComputeTypeFloat*/); } realObject16Bit = use16Bit; } } return(realObject); }
/// <summary>Releases the resources that are used by the object.</summary> public void Dispose() { EngineThreading.CheckMainThread(); DisposeInternal(); }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static Resource.Instance CreateResource(ResourceType resourceType, Resource.InstanceType instanceType, string name, bool wait, Metadata.TypeInfo createResultObjectWithType, bool componentCreateHierarchyController, bool?componentSetEnabled, out string error) { //!!!! if (!wait) { Log.Fatal("ResourceManager: CreateResource: wait == false. Background loading is not implemented."); } error = ""; //!!!!!threading if (string.IsNullOrEmpty(name)) { Log.Fatal("ResourceManager: CreateResource: The name can't be empty."); return(null); } Resource res; Resource.Instance ins; bool insCreated = false; lock ( lockObject ) { //get or create resource res = GetByName(name); if (res == null) { //!!!!override loader ConstructorInfo constructor = resourceType.resourceClass.GetConstructor(new Type[0]); res = (Resource)constructor.Invoke(new object[0]); res.resourceType = resourceType; res.name = name; res.loadFromFile = true; //add to the list resources.Add(GetKey(name), res); } //create instance if (instanceType == Resource.InstanceType.Resource) { //as Resource if (res.PrimaryInstance == null) { ins = res.CreateInstanceClassObject(instanceType, componentCreateHierarchyController, componentSetEnabled); res.PrimaryInstance = ins; insCreated = true; } else { ins = res.PrimaryInstance; } } else { //as Separate instance ins = res.CreateInstanceClassObject(instanceType, componentCreateHierarchyController, componentSetEnabled); insCreated = true; } } if (insCreated) { if (createResultObjectWithType != null) { object obj = createResultObjectWithType.InvokeInstance(null); var component = obj as Component; if (component != null) { if (componentSetEnabled != null) { component.Enabled = componentSetEnabled.Value; } if (componentCreateHierarchyController) { ComponentUtility.CreateHierarchyControllerForRootComponent(component, ins, true); //, true ); } } ins.ResultObject = obj; } //resource is ready ins.Status = Resource.Instance.StatusEnum.Ready; } ////_Load function //if( insCreated ) //{ // //load // if( wait ) // { // LoadTaskFunction( ins ); // } // else // { // Task task = new Task( LoadTaskFunction, ins ); // task.Start(); // } //} //wait if (wait) { //wait end of creation while (ins.Status == Resource.Instance.StatusEnum.CreationProcess) { //!!!!slow? maybe we can increase priority for this instance or something like this? if (VirtualFileSystem.MainThread == Thread.CurrentThread) { //process main thread tasks EngineThreading.ExecuteQueuedActionsFromMainThread(); } //!!!!? Thread.Sleep(0); } } //!!!!так? if (wait && ins.Status == Resource.Instance.StatusEnum.Error) { error = ins.StatusError; ins.Dispose(); return(null); } return(ins); }
public static Resource.Instance _Load(Resource.InstanceType instanceType, string name, bool wait, bool componentCreateHierarchyController, bool?componentSetEnabled, out string error) { error = ""; //!!!!!threading if (string.IsNullOrEmpty(name)) { error = ""; return(null); } //!!!!!на неналичие файла проверять. но не в локе? Resource res; Resource.Instance ins; bool insCreated = false; lock ( lockObject ) { //get or create resource res = GetByName(name); if (res == null) { //!!!!override loader var extension = Path.GetExtension(name); var resourceType = GetTypeByFileExtension(extension); if (resourceType == null) { //!!!!всё же как-то можно грузить? error = $"Loading of file type \'{extension}\' is not supported."; //error = ""; return(null); } ConstructorInfo constructor = resourceType.resourceClass.GetConstructor(new Type[0]); res = (Resource)constructor.Invoke(new object[0]); res.resourceType = resourceType; res.name = name; res.loadFromFile = true; //add to the list resources.Add(GetKey(name), res); } //create instance if (instanceType == Resource.InstanceType.Resource) { //as Resource if (res.PrimaryInstance == null) { ins = res.CreateInstanceClassObject(instanceType, componentCreateHierarchyController, componentSetEnabled); res.PrimaryInstance = ins; insCreated = true; } else { ins = res.PrimaryInstance; } } else { //as Separate instance ins = res.CreateInstanceClassObject(instanceType, componentCreateHierarchyController, componentSetEnabled); insCreated = true; } } //begin loading if (insCreated) { if (wait) { LoadTaskFunction(ins); } else { Task task = new Task(LoadTaskFunction, ins); task.Start(); } } //!!!!new //!!!!только InstanceType.Resource? //if wait == true and inside call ResourceManager._Load recursively with wait == true, then return null. if (wait && instanceType == Resource.InstanceType.Resource && !insCreated && ins.Status == Resource.Instance.StatusEnum.CreationProcess) { //так норм импорт работает, хотя это не совсем логично. return(ins); //return null; //xx; //ESet<Resource.Instance> waitLoadingResources = new ESet<Resource.Instance>(); //if( waitLoadingResources.Contains( ins ) ) // return null; //waitLoadingResources.Add( ins ); } //wait if (wait) { //wait end of creation while (ins.Status == Resource.Instance.StatusEnum.CreationProcess) { //!!!!slow? maybe we can increase priority for this instance or something like this? if (VirtualFileSystem.MainThread == Thread.CurrentThread) { //process main thread tasks EngineThreading.ExecuteQueuedActionsFromMainThread(); } //!!!!? Thread.Sleep(0); } } //!!!!так? if (wait && ins.Status == Resource.Instance.StatusEnum.Error) { error = ins.StatusError; ins.Dispose(); return(null); } return(ins); }
static unsafe void logListener_messageLogged(string message, OgreLogMessageLevel lml, bool maskDebug) { //!!!!только из основного может прийти? EngineThreading.CheckMainThread(); if (!_EnableInternalLogMessages) { return; } string text = "Renderer: " + message; bool logWrited = false; bool internalLogMessageCalled = false; if (lml == OgreLogMessageLevel.LML_CRITICAL || text.Contains("Error")) { string t = message; //remove prefix { string check1 = "OGRE EXCEPTION("; string check2 = "): "; if (t.Contains(check1) && t.Contains(check2)) { int index = t.IndexOf(check2) + check2.Length; t = t.Substring(index); } } if (!_InvisibleInternalLogMessages) { if (!resourcesInitialized) { resourceInitializationErrors.Add(t); } else { if (!t.Contains("Cannot locate resource ")) { if (!rendererAdditionInitialized && resourcesInitialized) { //Specific for RendererAddition Log.Fatal(t); } else { Log.Warning(t); } logWrited = true; } } } if (_InternalLogMessage != null) { _InternalLogMessage(t); } internalLogMessageCalled = true; } if (!logWrited) { Log.InvisibleInfo(text); } if (!internalLogMessageCalled) { if (_InternalLogMessage != null) { _InternalLogMessage(text); } } }