Пример #1
0
    private List <ModelBatch> BuildBatches(int modelIndex)
    {
        var model     = _bsp.Models[modelIndex];
        var batches   = new List <ModelBatch>();
        var firstFace = model.FirstFace;
        var numFaces  = model.NumFaces;

        // WorldSpawn is static geometry, so batch it together by material
        for (int i = firstFace; i < firstFace + numFaces; i++)
        {
            var face = _bsp.Faces[i];
            var ti   = _bsp.TextureInfos[face.TexInfo];

            ModelBatch batch = batches.FindLast(b => b.Ti.TexData == ti.TexData);
            if (batch == null)
            {
                batch = new ModelBatch();
                batches.Add(batch);
            }

            batch.FaceIds.Add(i);
            batch.Ti           = ti;
            batch.VertexCount += face.NumEdges;
            batch.TriCount    += (face.NumEdges - 2) * 3;
        }

        return(batches);
    }
Пример #2
0
        public override void create()
        {
            Gdx.app.log("Game", "Create");


            _batch           = new ModelBatch();
            _camera          = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            _camera.position = new Vector3(10f, 10f, 100f);
            _camera.lookAt(0f, 0f, 0f);
            _camera.near = 1;
            _camera.far  = 300;
            _camera.update();

            var loader = new ObjLoader();
            var data   = loader.loadModelData("brown_wall.obj");

            _model = new Model(data);

            for (int i = -10; i < 10; i++)
            {
                var modelInstance = new ModelInstance(_model, Matrix4.Identity, null);
                _modelInstances.Add(modelInstance);
            }
            Gdx.app.debug("TestModel", $"V: {Gdx.graphics.getWidth()}:{Gdx.graphics.getHeight()}  Models: {_modelInstances.Count}");
        }
Пример #3
0
        private GameObject BatchToObject(ModelBatch batch)
        {
            var verts      = new UVector3[batch.VertexCount];
            var normals    = new UVector3[batch.VertexCount];
            var tris       = new int[batch.TriCount];
            var uv         = new UVector2[batch.VertexCount];
            var uv2        = new UVector2[batch.VertexCount];
            var vertOffset = 0;
            var triOffset  = 0;

            foreach (int faceIndex in batch.FaceIds)
            {
                var face = _bsp.Faces[faceIndex];
                var ti   = _bsp.TextureInfos[face.TexInfo];

                if (ti.Flags.HasFlag(SurfFlags.NODRAW) ||
                    ti.Flags.HasFlag(SurfFlags.SKIP) ||
                    face.DispInfo != -1)
                {
                    continue;
                }

                BuildFace(faceIndex, ref verts, ref tris, ref uv, ref uv2, ref normals, vertOffset, triOffset);

                vertOffset += face.NumEdges;
                triOffset  += (face.NumEdges - 2) * 3;
            }

            var dataId       = _bsp.TextureData[batch.Ti.TexData].NameStringTableId;
            var materialPath = $"materials/{_bsp.GetTextureString(dataId)}.vmt";
            var obj          = CreateGameObject(materialPath);
            var mr           = obj.AddComponent <MeshRenderer>();
            var mf           = obj.AddComponent <MeshFilter>();

            mf.mesh           = new Mesh();
            mf.mesh.vertices  = verts;
            mf.mesh.triangles = tris;
            mf.mesh.normals   = normals;
            mf.mesh.uv        = uv;
            mf.mesh.uv2       = uv2;
            //mf.mesh.RecalculateNormals();
            //mf.mesh.RecalculateTangents();
            mf.mesh.RecalculateBounds();

            mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            mr.receiveShadows    = true;
            mr.lightmapIndex     = _currentLightmap;

            var vmtInfo = ApplyMaterial(mr, materialPath);

            if (vmtInfo != null)
            {
                CreateSurfacePropIdentifier(obj, vmtInfo.SurfaceProp);
            }

            return(obj);
        }
Пример #4
0
        public RopeTester()
        {
            const int Segments = 12;
            const int Length   = 30;

            rope          = new VerletRope(Segments, Length);
            rope.Position = new vec2(400, 300);

            models = new Model[Segments];
            Batch  = new ModelBatch(1000000, 100000);

            for (int i = 0; i < Segments; i++)
            {
                Model model = new Model("Chain.obj");
                models[i] = model;
                Batch.Add(model);
            }

            MessageSystem.Subscribe(this, CoreMessageTypes.Mouse, (messageType, data, dt) =>
            {
                ProcessMouse((MouseData)data);
            });
        }
Пример #5
0
        private void CreateResources(LoadedModelResources?modelResources, string?modelPath)
        {
            var isModelCached = _cachedResources.TryGetValue(modelPath ?? string.Empty, out var cachedResources);

            if (isModelCached)
            {
                _loadedResources = cachedResources.LoadedResources;
                _sharedResources = cachedResources.SharedResources;

                _batch = _modelBatches[cachedResources];
            }
            else
            {
                if (modelResources is null)
                {
                    using (var modelStream = GraphicsProvider.Path2ModelStream(modelPath !))
                    {
                        if (modelStream is null)
                        {
                            throw new FileNotFoundException(modelPath);
                        }

                        try
                        {
                            _loadedResources = ModelLoader.LoadModel(modelStream);
                        }
                        catch (Exception e)
                        {
                            throw new InvalidDataException($"Unable to load model: {modelPath}", e);
                        }
                    }
                }
                else
                {
                    _loadedResources = modelResources;
                }

                _sharedResources = CreateSharedResources(_loadedResources);

                cachedResources = new CachedModelResources
                {
                    LoadedResources = _loadedResources,
                    SharedResources = _sharedResources,
                };

                _batch = new ModelBatch
                {
                    Models = new HashSet <ModelInstance>(),
                };

                _modelBatches.Add(cachedResources, _batch);

                if (!string.IsNullOrEmpty(modelPath))
                {
                    _cachedResources.Add(modelPath, cachedResources);
                }
            }

            _instanceResources = CreateInstanceResources();

            _batch.Models.Add(this);
        }
Пример #6
0
 public Scene()
 {
     entities   = new List <Entity>();
     ModelBatch = new ModelBatch(100000, 10000);
 }
Пример #7
0
        private void LoadGame(object sender, EventArgs e)
        {
            GL.ClearColor(0, 0, 0, 0);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.ProgramPointSize);
            GL.Enable(EnableCap.CullFace);
            GL.PointSize(5);

            worldshader = new GLSLProgram()
                          .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/WorldVertex.glsl", ShaderType.VertexShader))
                          .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/WorldFragment.glsl", ShaderType.FragmentShader))
                          .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/WorldGeometry.glsl", ShaderType.GeometryShader))
                          .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/GammaCorrection.glsl", ShaderType.VertexShader))
                          .Link();

            ppshader = new GLSLProgram()
                       .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/PostProgressVertex.glsl", ShaderType.VertexShader))
                       .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/PostProgressFragment.glsl", ShaderType.FragmentShader))
                       .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/GammaCorrection.glsl", ShaderType.FragmentShader))
                       .Link();

            gaussianblurshader = new GLSLProgram()
                                 .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/PostProgressVertex.glsl", ShaderType.VertexShader))
                                 .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/GaussianBlurFragment.glsl", ShaderType.FragmentShader))
                                 .Link();

            bloomshader = new GLSLProgram()
                          .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/PostProgressVertex.glsl", ShaderType.VertexShader))
                          .AttachShaderAndDelete(GLSLShader.FromFile("./Data/Shader/FX/BloomFragment.glsl", ShaderType.FragmentShader))
                          .Link();


            gDepth    = new Texture2D(Width, Height, PixelInternalFormat.DepthComponent32f, PixelFormat.DepthComponent, PixelType.Float);
            gPosition = new Texture2D(Width, Height, PixelInternalFormat.Rgb32f, PixelFormat.Rgb, PixelType.Float);
            gNormal   = new Texture2D(Width, Height, PixelInternalFormat.Rgb16f, PixelFormat.Rgb, PixelType.HalfFloat);
            gAlbedo   = new Texture2D(Width, Height, PixelInternalFormat.Rgb, PixelFormat.Rgb, PixelType.UnsignedByte);
            gLight    = new Texture2D(Width, Height, PixelInternalFormat.Rgb, PixelFormat.Rgb, PixelType.UnsignedByte);

            gBuffer = new Framebuffer()
                      .AttachTexture(gDepth, FramebufferAttachment.DepthAttachment)
                      .AttachTexture(gPosition, FramebufferAttachment.ColorAttachment0)
                      .AttachTexture(gNormal, FramebufferAttachment.ColorAttachment1)
                      .AttachTexture(gAlbedo, FramebufferAttachment.ColorAttachment2)
                      .AttachTexture(gLight, FramebufferAttachment.ColorAttachment3);
            GL.DrawBuffers(4, new DrawBuffersEnum[] { DrawBuffersEnum.ColorAttachment0, DrawBuffersEnum.ColorAttachment1, DrawBuffersEnum.ColorAttachment2, DrawBuffersEnum.ColorAttachment3 });
            gBuffer.CheckStatus();
            gBuffer.Unbind();

            lightTexture = new Texture2D(Width, Height, PixelInternalFormat.Rgb16f, PixelFormat.Rgb, PixelType.HalfFloat);
            lightTexture.SetWarpMode(TextureWrapMode.ClampToEdge);
            lightBuffer = new Framebuffer()
                          .AttachTexture(lightTexture, FramebufferAttachment.ColorAttachment0);
            lightBuffer.CheckStatus();
            lightBuffer.Unbind();

            lightManager = new LightManager();

            for (int i = 0; i < 2; i++)
            {
                blurTexture[i] = new Texture2D((int)(Width / 2f), (int)(Height / 2f), PixelInternalFormat.Rgb16f, PixelFormat.Rgb, PixelType.HalfFloat);
                blurTexture[i].SetFiltering(TextureMinFilter.Linear, TextureMagFilter.Linear);
                blurFramebuffer[i] = new Framebuffer().AttachTexture(blurTexture[i], FramebufferAttachment.ColorAttachment0);
                if (!blurFramebuffer[i].CheckStatus())
                {
                    Console.WriteLine("Framebuffer error");
                }
                blurFramebuffer[i].Unbind();
            }

            bloomTexture = new Texture2D((int)(Width / 1f), (int)(Height / 1f), PixelInternalFormat.Rgb16f, PixelFormat.Rgb, PixelType.HalfFloat);
            bloomTexture.SetFiltering(TextureMinFilter.Linear, TextureMagFilter.Linear);
            bloomFramebuffer = new Framebuffer().AttachTexture(bloomTexture, FramebufferAttachment.ColorAttachment0);
            if (!bloomFramebuffer.CheckStatus())
            {
                Console.WriteLine("Framebuffer error");
            }
            bloomFramebuffer.Unbind();

            model = new ModelBatch();

            lsr = new LightScatteringRenderer(Width, Height);
        }
Пример #8
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);


            Keyboard.KeyDown += (object sender, KeyboardKeyEventArgs key) => {
                if (key.Key == Key.F12)
                {
                    if (VSync == VSyncMode.Off)
                    {
                        VSync = VSyncMode.Adaptive;
                    }
                    else
                    {
                        VSync = VSyncMode.Off;
                    }
                }
                if (key.Key == Key.F11)
                {
                    if (WindowState != WindowState.Fullscreen)
                    {
                        WindowState = WindowState.Fullscreen;
                    }
                    else
                    {
                        WindowState = WindowState.Normal;
                    }
                }
                if (key.Key == Key.F10)
                {
                    Wireframe = !Wireframe;
                }
                if (key.Key == Key.F9)
                {
                    Bloom = !Bloom;
                }
                if (key.Key == Key.F8)
                {
                    Fxaa = !Fxaa;
                }
                if (key.Key == Key.F7)
                {
                    LightScattering = !LightScattering;
                }
                if (key.Key == Key.F1)
                {
                    ModelBatch.RowOrder = !ModelBatch.RowOrder;
                }
                if (key.Key == Key.F6)
                {
                    sun.Color = (sun.Color.Length == 0 ? new Vector3(1, 1, 1) : new Vector3(0, 0, 0));
                }
                if (key.Key == Key.Tab)
                {
                    Root.Remove(monkeynode);
                    Root.Add(monkeynode = new GameObject());
                }
                if (key.Key == Key.Space)
                {
                    monkeynode.Add(new ModelRenderer(monkey, new Matrix4(1, 0, 0, Camera.Position.X,
                                                                         0, 1, 0, Camera.Position.Y,
                                                                         0, 0, 1, Camera.Position.Z,
                                                                         0, 0, 0, 1) * Matrix4.CreateFromQuaternion(Camera.Rotation) * Matrix4.CreateRotationY((float)Math.PI)));
                }
            };
            Mouse.ButtonDown += (object sender, MouseButtonEventArgs key) => {
                if (CursorVisible == false)
                {
                    if (key.Button == MouseButton.Left)
                    {
                        Random rew = new Random();
                        monkeynode.Add(new PointLight(Camera.Position).SetColor(new Vector3((float)rew.NextDouble(), (float)rew.NextDouble(), (float)rew.NextDouble()) * 4));
                    }
                    if (key.Button == MouseButton.Middle)
                    {
                        Random rew = new Random();
                        monkeynode.Add(new DirectionalLight(Camera.Forward).SetColor(new Vector3((float)rew.NextDouble(), (float)rew.NextDouble(), (float)rew.NextDouble()) * 0.5f));
                    }
                    if (key.Button == MouseButton.Right)
                    {
                        Random rew = new Random();
                        monkeynode.Add(new SpotLight(Camera.Position, Camera.Forward).SetCLQ(1, 0.09f, 0.0001f).SetColor(new Vector3((float)rew.NextDouble(), (float)rew.NextDouble(), (float)rew.NextDouble()) * 4));
                    }
                }
            };

            AmbientLight = new Vector3(0.1f, 0.1f, 0.1f);

            sun  = new DirectionalLight(new Vector3(0, -1, 0));
            time = 30;
            Root.Add(sun);
            Root.Add(new LightScatteringComponent(new Vector3(1.0f, 0.8f, 0.3f)));


            monkey = ModelBatch.LoadModel(Faces.FromFile(@".\Data\Model\Monkey.lpm"));//new Model(faces)
            Root.Add((specialmonkey = new ModelRenderer(monkey, Matrix4.Identity)));
            Root.Add(new ModelRenderer(ModelBatch.LoadModel(Faces.FromFile(@".\Data\Model\World.lpm"))));
            Root.Add(monkeynode = new GameObject());
        }