Пример #1
0
        public CubeMap UpdateMap()
        {
            Dictionary <string, Godot.CubeMap.Side> images = new Dictionary <string, Godot.CubeMap.Side>();

            images.Add("left", CubeMap.Side.Left);
            images.Add("right", CubeMap.Side.Right);
            images.Add("front", CubeMap.Side.Front);
            images.Add("back", CubeMap.Side.Back);
            images.Add("top", CubeMap.Side.Top);
            images.Add("bottom", CubeMap.Side.Bottom);

            var cube_map = new CubeMap();

            foreach (Viewport i in GetChildren())
            {
                if (images.ContainsKey(i.Name))
                {
                    var img = new Image();
                    img.CopyFrom(i.GetTexture().GetData());
                    cube_map.SetSide(images[i.Name], img);
                }
            }

            return(cube_map);
        }
Пример #2
0
    // Start is called before the first frame update
    void Start()
    {
        SetRayTransforms();
        cubeState = FindObjectOfType <CubeState>();
        cubeMap   = FindObjectOfType <CubeMap>();

        ReadState();
        CubeState.started = true;
        //List<GameObject> facesHit = new List<GameObject>();


        //Vector3 ray = tFront.transform.position;
        //RaycastHit hit;

        //// Intersecteaza raza vreun obiect in layerMask?
        //if (Physics.Raycast(ray, tFront.right, out hit, Mathf.Infinity, layerMask))
        //{
        //    Debug.DrawRay(ray, tFront.right * hit.distance, Color.yellow);
        //    facesHit.Add(hit.collider.gameObject);
        //    //print(hit.collider.gameObject.name);
        //}
        //else
        //{
        //    Debug.DrawRay(ray, tFront.right * 1000, Color.green);
        //}
        //cubeState.front = facesHit;
        //cubeMap.Set();
    }
Пример #3
0
    public void InitBaseAtPosition()
    {
        CubeMap    cubeMap        = CubeMapController.Instance.CubeMapData;
        GameObject cubeController = CubeMapController.Instance.GetCubeGO(cubeMap.Width / 2, cubeMap.Depth / 2);

        this.BaseGO = Instantiate(this.BasePrefab, this.transform) as GameObject;
        this.BaseGO.transform.position = cubeController.transform.position;

        this.BaseGO.GetComponent <HomeBaseController> ().SetHomeBaseData(this.GameData.HomeBaseData);
    }
    // Start is called before the first frame update
    void Start()
    {
        SetRayTransforms();

        cubeState = FindObjectOfType <CubeState>();
        cubeMap   = FindObjectOfType <CubeMap>();

        ReadState();
        CubeState.started = true;
    }
Пример #5
0
        public void ShouldAlignColorsAtCorners()
        {
            var orange = new Color(1f, 0.5f, 0f);
            var left   = new UVAlignTestPattern(Colors.Yellow, Colors.Cyan, Colors.Red, Colors.Blue, orange);
            var front  = new UVAlignTestPattern(Colors.Cyan, Colors.Red, Colors.Yellow, orange, Colors.Green);
            var right  = new UVAlignTestPattern(Colors.Red, Colors.Yellow, Colors.Magenta, Colors.Green, Colors.White);
            var back   = new UVAlignTestPattern(Colors.Green, Colors.Magenta, Colors.Cyan, Colors.White, Colors.Blue);
            var top    = new UVAlignTestPattern(orange, Colors.Cyan, Colors.Magenta, Colors.Red, Colors.Yellow);
            var bottom = new UVAlignTestPattern(Colors.Magenta, orange, Colors.Green, Colors.Blue, Colors.White);
            var map    = new CubeMap(left, front, right, back, top, bottom);
            var corner = 0.9f;

            // Left
            map.LocalColorAt(new Point(-1, 0, 0)).Should().Be(Colors.Yellow);
            map.LocalColorAt(new Point(-1, corner, -corner)).Should().Be(Colors.Cyan);
            map.LocalColorAt(new Point(-1, corner, corner)).Should().Be(Colors.Red);
            map.LocalColorAt(new Point(-1, -corner, -corner)).Should().Be(Colors.Blue);
            map.LocalColorAt(new Point(-1, -corner, corner)).Should().Be(orange);

            // Front
            map.LocalColorAt(new Point(0, 0, 1)).Should().Be(Colors.Cyan);
            map.LocalColorAt(new Point(corner, -corner, 1)).Should().Be(Colors.Green);
            map.LocalColorAt(new Point(corner, corner, 1)).Should().Be(Colors.Yellow);
            map.LocalColorAt(new Point(-corner, -corner, 1)).Should().Be(orange);
            map.LocalColorAt(new Point(-corner, corner, 1)).Should().Be(Colors.Red);

            // Right
            map.LocalColorAt(new Point(1, 0, 0)).Should().Be(Colors.Red);
            map.LocalColorAt(new Point(1, corner, -corner)).Should().Be(Colors.Magenta);
            map.LocalColorAt(new Point(1, corner, corner)).Should().Be(Colors.Yellow);
            map.LocalColorAt(new Point(1, -corner, -corner)).Should().Be(Colors.White);
            map.LocalColorAt(new Point(1, -corner, corner)).Should().Be(Colors.Green);

            // Back
            map.LocalColorAt(new Point(0, 0, -1)).Should().Be(Colors.Green);
            map.LocalColorAt(new Point(corner, -corner, -1)).Should().Be(Colors.White);
            map.LocalColorAt(new Point(corner, corner, -1)).Should().Be(Colors.Magenta);
            map.LocalColorAt(new Point(-corner, -corner, -1)).Should().Be(Colors.Blue);
            map.LocalColorAt(new Point(-corner, corner, -1)).Should().Be(Colors.Cyan);

            // Top
            map.LocalColorAt(new Point(0, 1, 0)).Should().Be(orange);
            map.LocalColorAt(new Point(corner, 1, -corner)).Should().Be(Colors.Magenta);
            map.LocalColorAt(new Point(corner, 1, corner)).Should().Be(Colors.Yellow);
            map.LocalColorAt(new Point(-corner, 1, -corner)).Should().Be(Colors.Cyan);
            map.LocalColorAt(new Point(-corner, 1, corner)).Should().Be(Colors.Red);

            // Bottom
            map.LocalColorAt(new Point(0, -1, 0)).Should().Be(Colors.Magenta);
            map.LocalColorAt(new Point(corner, -1, -corner)).Should().Be(Colors.White);
            map.LocalColorAt(new Point(corner, -1, corner)).Should().Be(Colors.Green);
            map.LocalColorAt(new Point(-corner, -1, -corner)).Should().Be(Colors.Blue);
            map.LocalColorAt(new Point(-corner, -1, corner)).Should().Be(orange);
        }
Пример #6
0
        public static Skybox Find(string name, Color skycolor)
        {
            var skybox = new Skybox(name, skycolor);

            skybox.texture = CubeMap.Find($"Skyboxes/{name}");
            mesh           = mesh ?? new Mesh()
            {
                shape = SkyboxShape.Geometry
            };
            return(skybox);
        }
    public void ReadState()
    {
        cubeState = FindObjectOfType <CubeState>();
        cubeMap   = FindObjectOfType <CubeMap>();

        cubeState.up    = ReadFace(upRays, tUp);
        cubeState.down  = ReadFace(downRays, tDown);
        cubeState.left  = ReadFace(leftRays, tLeft);
        cubeState.right = ReadFace(rightRays, tRight);
        cubeState.front = ReadFace(frontRays, tFront);
        cubeState.back  = ReadFace(backRays, tBack);

        cubeMap.Set();
    }
Пример #8
0
 public CubeMapEditorForm(CubeMap cubeMap)
 {
     this.InitializeComponent();
     this.cubeMap = cubeMap;
     if (!String.IsNullOrEmpty(cubeMap.BasePath))
     {
         this.txtPathBase.Text = cubeMap.BasePath;
     }
     if (!String.IsNullOrEmpty(cubeMap.FileNamePattern))
     {
         this.ddlNamePrefix.SelectedItem = cubeMap.FileNamePattern;
     }
     this.numericUpDown1.Value = Convert.ToDecimal(cubeMap.Width);
     this.numericUpDown2.Value = Convert.ToDecimal(cubeMap.Height);
     this.numericUpDown3.Value = Convert.ToDecimal(cubeMap.Depth);
 }
Пример #9
0
    public void ReadState()
    {
        cubeState = FindObjectOfType <CubeState>();
        cubeMap   = FindObjectOfType <CubeMap>();

        // set the state of each position in the list of sides so we know
        // what color is in what position
        cubeState.up    = ReadFace(upRays, tUp);
        cubeState.down  = ReadFace(downRays, tDown);
        cubeState.left  = ReadFace(leftRays, tLeft);
        cubeState.right = ReadFace(rightRays, tRight);
        cubeState.front = ReadFace(frontRays, tFront);
        cubeState.back  = ReadFace(backRays, tBack);

        // update the map with the found positions
        cubeMap.Set();
    }
Пример #10
0
    public void ReadState()
    {
        cubeState = FindObjectOfType <CubeState>();
        cubeMap   = FindObjectOfType <CubeMap>();

        //readface는 6번 도니까 6번 타이핑할거임
        //여기 readCube 스크립트에서 바로 CubeState의 up을 업로드해줄거임
        cubeState.up = ReadFace(upRays, tUp);
        //tUp은 start하자마자 SetRayTransforms()함수에서 buildray()함수로 90도 돌려서 중앙을 바라보고있음
        cubeState.down  = ReadFace(downRays, tDown);
        cubeState.left  = ReadFace(leftRays, tLeft);
        cubeState.right = ReadFace(rightRays, tRight);
        cubeState.front = ReadFace(frontRays, tFront);
        cubeState.back  = ReadFace(backRays, tBack);

        // CubeState 구청에 모든 서류가 전달되었으므로 Set()함수씀
        cubeMap.Set(); //CubeState 구청자료를 cubeMap현장 ui패널에 대입
    }
Пример #11
0
        public void FindingTheColorsOnMappedCube_ShouldWork(Point point, Color expected)
        {
            var red     = new Color(1, 0, 0);
            var yellow  = new Color(1, 1, 0);
            var brown   = new Color(1, 0.5, 0);
            var green   = new Color(0, 1, 0);
            var cyan    = new Color(0, 1, 1);
            var blue    = new Color(0, 0, 1);
            var purple  = new Color(1, 0, 1);
            var white   = new Color(1, 1, 1);
            var left    = new UvAlignCheck(yellow, cyan, red, blue, brown);
            var front   = new UvAlignCheck(cyan, red, yellow, brown, green);
            var right   = new UvAlignCheck(red, yellow, purple, green, white);
            var back    = new UvAlignCheck(green, purple, cyan, white, blue);
            var up      = new UvAlignCheck(brown, cyan, purple, red, yellow);
            var down    = new UvAlignCheck(purple, brown, green, blue, white);
            var pattern = new CubeMap(left, front, right, back, up, down);

            Assert.Equal(expected, pattern.PatternAt(point));
        }
Пример #12
0
        public void Load(IAssetManager assetManager)
        {
            _texture = new CubeMap();
            _texture.Bind();

            _texture.Param(TextureParameterName.TextureWrapS, TextureWrapMode.ClampToEdge);
            _texture.Param(TextureParameterName.TextureWrapT, TextureWrapMode.ClampToEdge);
            _texture.Param(TextureParameterName.TextureMagFilter, TextureMagFilter.Linear);
            _texture.Param(TextureParameterName.TextureMinFilter, TextureMinFilter.Linear);

            for (var i = 0; i < 6; i++)
            {
                var textureName = new Identifier(_name.Namespace, _name.Key + '_' + i + ".png");
                if (!assetManager.TryLoad <Bitmap>(textureName, out var image))
                {
                    throw new FileNotFoundException("Texture not found");
                }

                _texture.SetIndex((CubeMap.TextureIndex)i);
                _texture.Data(image);
            }
        }
Пример #13
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            string pattern = this.ddlNamePrefix.SelectedItem as String;

            if (!String.IsNullOrEmpty(pattern))
            {
                this.cubeMap = new CubeMap(Convert.ToSingle(this.numericUpDown1.Value),
                                           Convert.ToSingle(this.numericUpDown2.Value),
                                           Convert.ToSingle(this.numericUpDown3.Value), this.txtPathBase.Text, pattern);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                if (
                    MessageBox.Show("The file name pattern is empty! Close dialog anyway?", "Choose a pattern...",
                                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
            }
        }
Пример #14
0
            public virtual void ReadChildData(BinaryReader reader)
            {
                int x = 0;

                _renderModel.ReadString(reader);
                _animationGraph.ReadString(reader);
                for (x = 0; (x < _cubeMap.Count); x = (x + 1))
                {
                    CubeMap.Add(new SkyCubemapBlockBlock());
                    CubeMap[x].Read(reader);
                }
                for (x = 0; (x < _cubeMap.Count); x = (x + 1))
                {
                    CubeMap[x].ReadChildData(reader);
                }
                for (x = 0; (x < _atmosphericFog.Count); x = (x + 1))
                {
                    AtmosphericFog.Add(new SkyAtmosphericFogBlockBlock());
                    AtmosphericFog[x].Read(reader);
                }
                for (x = 0; (x < _atmosphericFog.Count); x = (x + 1))
                {
                    AtmosphericFog[x].ReadChildData(reader);
                }
                for (x = 0; (x < _secondaryFog.Count); x = (x + 1))
                {
                    SecondaryFog.Add(new SkyAtmosphericFogBlockBlock());
                    SecondaryFog[x].Read(reader);
                }
                for (x = 0; (x < _secondaryFog.Count); x = (x + 1))
                {
                    SecondaryFog[x].ReadChildData(reader);
                }
                for (x = 0; (x < _skyFog.Count); x = (x + 1))
                {
                    SkyFog.Add(new SkyFogBlockBlock());
                    SkyFog[x].Read(reader);
                }
                for (x = 0; (x < _skyFog.Count); x = (x + 1))
                {
                    SkyFog[x].ReadChildData(reader);
                }
                for (x = 0; (x < _patchyFog.Count); x = (x + 1))
                {
                    PatchyFog.Add(new SkyPatchyFogBlockBlock());
                    PatchyFog[x].Read(reader);
                }
                for (x = 0; (x < _patchyFog.Count); x = (x + 1))
                {
                    PatchyFog[x].ReadChildData(reader);
                }
                for (x = 0; (x < _lights.Count); x = (x + 1))
                {
                    Lights.Add(new SkyLightBlockBlock());
                    Lights[x].Read(reader);
                }
                for (x = 0; (x < _lights.Count); x = (x + 1))
                {
                    Lights[x].ReadChildData(reader);
                }
                for (x = 0; (x < _shaderFunctions.Count); x = (x + 1))
                {
                    ShaderFunctions.Add(new SkyShaderFunctionBlockBlock());
                    ShaderFunctions[x].Read(reader);
                }
                for (x = 0; (x < _shaderFunctions.Count); x = (x + 1))
                {
                    ShaderFunctions[x].ReadChildData(reader);
                }
                for (x = 0; (x < _animations.Count); x = (x + 1))
                {
                    Animations.Add(new SkyAnimationBlockBlock());
                    Animations[x].Read(reader);
                }
                for (x = 0; (x < _animations.Count); x = (x + 1))
                {
                    Animations[x].ReadChildData(reader);
                }
            }
Пример #15
0
        private void Update(EvaluationContext context)
        {
            var updateLive = UpdateLive.GetValue(context);

            if (_updatedOnce && !updateLive)
            {
                FilteredCubeMap.Value = _prefilteredCubeMap;
                return;
            }

            var exposure = Exposure.GetValue(context);

            //ConstantBuffers.GetValues(ref _constantBuffers, context);
            ShaderResources.GetValues(ref _shaderResourceViews, context);
            SamplerStates.GetValues(ref _samplerStates, context);

            var vs = VertexShader.GetValue(context);
            var gs = GeometryShader.GetValue(context);

            if (CubeMap.IsConnected && CubeMap.DirtyFlag.IsDirty)
            {
                //Log.Debug("Dirty");
            }

            var cubeMapSrc = CubeMap.GetValue(context); // Needs to be checked for null!

            if (cubeMapSrc == null)
            {
                FilteredCubeMap.Value = null;
                return;
            }

            var device        = ResourceManager.Instance().Device;
            var deviceContext = device.ImmediateContext;

            // Vertex shader stage
            var vsStage = deviceContext.VertexShader;

            _prevVsConstantBuffers     = vsStage.GetConstantBuffers(0, 1);
            _prevVsShaderResourceViews = vsStage.GetShaderResources(0, _shaderResourceViews.Length);
            _prevVertexShader          = vsStage.Get();

            if (vs == null)
            {
                Log.Warning($"{nameof(_SpecularPrefilter)} requires valid vertex shader", SymbolChildId);
                return;
            }
            vsStage.Set(vs);
            vsStage.SetShaderResources(0, _shaderResourceViews.Length, _shaderResourceViews);

            // Geometry shader stage
            var gsStage = deviceContext.GeometryShader;

            _prevGsConstantBuffers     = gsStage.GetConstantBuffers(0, 1);
            _prevGsShaderResourceViews = gsStage.GetShaderResources(0, _shaderResourceViews.Length);
            _prevGeometryShader        = gsStage.Get();

            if (gs == null)
            {
                Log.Warning($"{nameof(_SpecularPrefilter)} requires valid geometry shader", SymbolChildId);
                return;
            }

            gsStage.Set(gs);
            gsStage.SetShaderResources(0, _shaderResourceViews.Length, _shaderResourceViews);

            // Pixel shader stage
            var psStage = deviceContext.PixelShader;

            _prevPixelShader           = psStage.Get();
            _prevPsConstantBuffers     = psStage.GetConstantBuffers(0, 1);
            _prevPsShaderResourceViews = psStage.GetShaderResources(0, _shaderResourceViews.Length);
            _prevPsSamplerStates       = psStage.GetSamplers(0, _samplerStates.Length);

            var ps = PixelShader.GetValue(context);

            if (ps == null)
            {
                Log.Warning($"{nameof(_SpecularPrefilter)} requires valid pixel shader", SymbolChildId);
                return;
            }
            psStage.Set(ps);
            psStage.SetShaderResources(0, _shaderResourceViews.Length, _shaderResourceViews);
            psStage.SetSamplers(0, _samplerStates);


            // if (_prefilteredCubeMap != null && !Changed)
            // {
            //     context.Image = _prefilteredCubeMap;
            //     return context;
            // }

            Vector2 cubeMapSize = new Vector2(cubeMapSrc.Description.Width, cubeMapSrc.Description.Height);
            // Log.Debug($"source size: {cubeMapSrc.Description.Width} num mips in src: {cubeMapSrc.Description.MipLevels}");

            // if ( _prefilteredCubeMap == null )
            // {
            var cubeMapDesc = new Texture2DDescription
            {
                BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                Format            = cubeMapSrc.Description.Format,
                Width             = (int)cubeMapSize.X,
                Height            = (int)cubeMapSize.Y,
                MipLevels         = cubeMapSrc.Description.MipLevels,
                SampleDescription = cubeMapSrc.Description.SampleDescription,
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.TextureCube | ResourceOptionFlags.GenerateMipMaps,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 6
            };

            Utilities.Dispose(ref _prefilteredCubeMap);
            try
            {
                _prefilteredCubeMap = new Texture2D(device, cubeMapDesc);
            }
            catch (SharpDXException e)
            {
                Log.Debug($"can't create CubeMap target {e.Message}");
                return;
            }

            var rastDesc = new RasterizerStateDescription
            {
                FillMode           = FillMode.Solid,
                CullMode           = CullMode.None,
                IsDepthClipEnabled = false
            };

            _rasterizerState = new RasterizerState(device, rastDesc);

            // Input Assembler
            var previousTopology = device.ImmediateContext.InputAssembler.PrimitiveTopology;

            device.ImmediateContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;

            _prevBlendState = device.ImmediateContext.OutputMerger.GetBlendState(out _prevBlendFactor, out _prevSampleMask);
            device.ImmediateContext.OutputMerger.BlendState        = DefaultRenderingStates.DisabledBlendState;
            device.ImmediateContext.OutputMerger.DepthStencilState = DefaultRenderingStates.DisabledDepthStencilState;

            _prevRenderTargetViews = device.ImmediateContext.OutputMerger.GetRenderTargets(1);
            device.ImmediateContext.OutputMerger.GetRenderTargets(out _prevDepthStencilView);

            var rtvDesc = new RenderTargetViewDescription()
            {
                Dimension      = RenderTargetViewDimension.Texture2DArray,
                Format         = cubeMapSrc.Description.Format,
                Texture2DArray = new RenderTargetViewDescription.Texture2DArrayResource()
                {
                    ArraySize       = 6,
                    FirstArraySlice = 0,
                    MipSlice        = 0
                }
            };

            int size = _prefilteredCubeMap.Description.Width;

            _prevViewports = device.ImmediateContext.Rasterizer.GetViewports <RawViewportF>();

            device.ImmediateContext.Rasterizer.State = _rasterizerState;

            int numMipLevels = _prefilteredCubeMap.Description.MipLevels;
            int mipSlice     = 0;

            while (mipSlice < numMipLevels)
            {
                // Log.Debug($"Update mipmap level {mipSlice} size: {size}");
                var viewport = new RawViewportF {
                    X = 0, Y = 0, Width = size, Height = size, MinDepth = 0, MaxDepth = 1
                };
                device.ImmediateContext.Rasterizer.SetViewports(new[] { viewport });


                Utilities.Dispose(ref _cubeMapRtv);
                rtvDesc.Texture2DArray.MipSlice = mipSlice;
                _cubeMapRtv = new RenderTargetView(device, _prefilteredCubeMap, rtvDesc);
                device.ImmediateContext.OutputMerger.SetTargets(_cubeMapRtv, null);

                var roughness = (float)mipSlice / (_prefilteredCubeMap.Description.MipLevels - 1);

                // Is this required?
                if (_settingsBuffer != null)
                {
                    Utilities.Dispose(ref _settingsBuffer);
                }

                for (int i = 0; i < _samplingParameters.Length; ++i)
                {
                    int indexToUse = -1;
                    if (Math.Abs(roughness - _samplingParameters[i].roughness) < 0.001f)
                    {
                        indexToUse = i;
                    }

                    if (indexToUse == -1 && roughness < _samplingParameters[i].roughness)
                    {
                        indexToUse = i - 1;
                    }

                    if (indexToUse != -1)
                    {
                        var parameterData = _samplingParameters[indexToUse];
                        parameterData.roughness = roughness;
                        parameterData.exposure  = exposure;
                        ResourceManager.Instance().SetupConstBuffer(parameterData, ref _settingsBuffer);
                        break;
                    }
                }

                var constantBuffers = new[] { _settingsBuffer };
                psStage.SetConstantBuffers(0, 1, constantBuffers);
                vsStage.SetConstantBuffers(0, 1, constantBuffers);
                gsStage.SetConstantBuffers(0, 1, constantBuffers);

                device.ImmediateContext.Draw(3, 0);
                size /= 2;
                ++mipSlice;
            }

            FilteredCubeMap.Value = _prefilteredCubeMap;
            Utilities.Dispose(ref _cubeMapRtv);

            //device.ImmediateContext.InputAssembler.PrimitiveTopology = previousTopology;
            Restore(context);
            _updatedOnce = true;
        }
Пример #16
0
 public void SetCubeMap(ShaderResourceView cubemap)
 {
     CubeMap.SetResource(cubemap);
 }
Пример #17
0
 protected override void CreateShadowMap()
 {
     Program.Settings.GetShadowMapSize(out int width, out int height);
     ShadowMap = new CubeMap(width, height, InternalFormat.DepthComponent, PixelFormat.DepthComponent, PixelType.Float);
 }
    /// <summary>
    /// 初始化
    /// </summary>
    public SoftRenderForm()
    {
        Height = screenHeight;
        Width  = screenWidth;

        // 初始化前置缓冲区
        g = this.CreateGraphics();

        // 初始化屏幕缓冲区
        screenBuffer         = new Bitmap(screenWidth + 1, screenHeight + 1);
        screenBufferGraphics = Graphics.FromImage(screenBuffer);

        // 初始化深度缓冲区
        ZBuffer = new float[screenWidth + 1, screenHeight + 1];

        // 初始化所有光源
        directionalLight = new DirectionalLight(MainLightDirection, Color01.White);
        lights.Add(directionalLight);
        //pointLight = new PointLight(Vector3.Zero, 7, new Color01(0, 0, 1f, 1f));
        //lights.Add(pointLight);
        //spotLight = new SpotLight(15f, 7f, new Vector3(0, 0, 1), new Color01(1, 0, 0, 1), new Vector3(0, 0, -3));
        //lights.Add(spotLight);

        // 开启深度测试
        IsZTest = true;
        // 开启深度写入
        IsZWritting = true;

        // 开启光照渲染
        LightingOn = true;

        // 开启逐像素计算
        fragmentShaderOn = true;

        // 初始化摄像机
        camera = new Camera();

        // 读取贴图
        texture2D = new Bitmap("C:\\Users\\Administrator\\Desktop\\29126173.bmp");

        // 读取法线贴图
        normalTexture = new Bitmap(256, 256);
        //normalTexture = new Bitmap("D:\\UnityInstance\\Shader Collection\\Assets\\Textures\\Chapter7\\Brick_Normal.bmp");

        // 读取OBJ文件
        SpaceShip = OBJLoader.LoadOBJ("../../enemry_spaceship.obj");
        cube      = OBJLoader.LoadOBJ("../../cube.obj");
        //cube = new Cube();
        sphere     = OBJLoader.LoadOBJ("../../sphere.obj");
        skyBoxMesh = cube;

        // 初始化天空盒
        skyBox = new CubeMap(
            // front
            new Bitmap("../../frontImage.png"),
            // back
            new Bitmap("../../backImage.png"),
            // left
            new Bitmap("../../leftImage.png"),
            // right
            new Bitmap("../../rightImage.png"),
            // top
            new Bitmap("../../upImage.png"),
            // bottom
            new Bitmap("../../downImage.png")
            );

        StartRender();
    }
    /// <summary>
    /// 对应任意一种情况的光栅化线段的方法,
    /// 是Bresenham朴素算法的优化版,不出现浮点运算
    /// </summary>
    /// <param name="x1"></param>
    /// <param name="y1"></param>
    /// <param name="x2"></param>
    /// <param name="y2"></param>
    /// <param name="color"></param>
    private void DrawLine(Vertex v1, Vertex v2)
    {
        int x1 = (int)v1.pos.X;
        int y1 = (int)v1.pos.Y;
        int x2 = (int)v2.pos.X;
        int y2 = (int)v2.pos.Y;

        // 线段起点与终点在x轴上的距离(可能为负)
        int dx = x2 - x1;
        // 线段起点和终点在y轴上的距离(可能为负)
        int dy = y2 - y1;

        // 计算从x1到x2的方向是正方向还是负方向
        // 1<<1 = 2; 0<<1 = 0
        int stepX = ((dx > 0 ? 1 : 0) << 1) - 1;
        // 计算从y1到y2的方向是正方向还是负方向
        int stepY = ((dy > 0 ? 1 : 0) << 1) - 1;

        dx = Math.Abs(dx); dy = Math.Abs(dy);

        // 误差
        int eps = 0;

        if (dx > dy)
        {
            int y = y1;
            // 当x轴距离差更大时,将x作为自增变量
            for (int x = x1; x != x2; x += stepX)
            {
                float t = (float)(x - x1) / (float)(x2 - x1);

                // 当前顶点
                Vertex vertex = Vertex.LerpVertexData(v1, v2, t);
                vertex.pos.X = x;
                vertex.pos.Y = y;

                float z = vertex.pos.Z;

                // 对当前像素进行深度测试
                if (IsZTest)
                {
                    if (!ZTest(x, y, z))
                    {
                        continue;
                    }
                }

                // 透视插值矫正
                float realZ = 1.0f / z;
                vertex.u *= realZ;      // 变回原来的u
                vertex.v *= realZ;      // 变回原来的v

                float u = vertex.u;
                float v = vertex.v;

                // 对顶点颜色进行插值
                Color01 color = Color01.LerpColor(v1.color, v2.color, t);

                // 对纹理贴图进行采样
                Color01 textureColor = Texture.Tex2D(texture2D, u, v);

                Color01 finalColor = textureColor * color;

                if (drawingSkyBox)
                {
                    finalColor = CubeMap.TexCube(skyBox, vertex.modelSpacePos);
                    DrawPixel(x, y, finalColor);
                }
                else if (fragmentShaderOn)
                {
                    // 对所有光源进行着色器计算,然后将所有光源的结果叠加起来
                    // 即该片元的颜色由所有光源决定

                    finalColor = Color01.Black;

                    foreach (var light in lights)
                    {
                        finalColor += FragmentShader(vertex, light);
                    }

                    DrawPixel(x, y, finalColor);
                }
                else
                {
                    DrawPixel(x, y, finalColor);
                }

                // 增量误差
                eps += dy;

                // 误差大于0.5,那么y++
                if ((eps << 1) >= dx)
                {
                    y   += stepY;
                    eps -= dx;
                }
            }
        }
        else
        {
            int x = x1;
            // 当y轴距离差更大时,将y作为自增变量
            for (int y = y1; y != y2; y += stepY)
            {
                float t = (float)(y - y1) / (float)(y2 - y1);

                Color01 color = Color01.LerpColor(v1.color, v2.color, t);
                DrawPixel(x, y, color);

                // 增量误差
                eps += dx;

                if ((eps << 1) >= dy)
                {
                    x   += stepX;
                    eps -= dy;
                }
            }
        }
    }
Пример #20
0
        override protected void CreateResources()
        {
            RgbaFloat lightColor = RgbaFloat.White;
            // RgbaFloat lightColor = RgbaFloat.LightGrey;
            //var lightPos = new Vector4(-0.5f,0.1f,10,1);
            var lightPos = new Vector4(0.0f, 0.0f, 0, 1);
            var lookAt   = new Vector4(0, 0, 0, 1) - new Vector4(0, 1, 0, 1);

            //var lightCam = new OrthographicCamera(50.0f, 50.0f, lightPos, lookAt);
            //_sceneRuntimeState.Light = new Light(lightCam,lightColor,0.1f);
            _sceneRuntimeState.Camera    = Camera;
            _sceneRuntimeState.SpotLight = Light.NO_POINTLIGHT;

            var omniCameras = CubeMap.GenerateOmniCameras(lightPos, 1024, 1024);

            _sceneRuntimeState.OmniLights = Light.GenerateOmniLights(omniCameras, lightColor, 0.1f);

            // string filePath = Path.Combine(AppContext.BaseDirectory, "armor/armor.dae");
            // string filePath = Path.Combine(AppContext.BaseDirectory, "nanosuit/nanosuit.obj");

            var scale = Matrix4x4.CreateScale(0.05f, 0.05f, 0.05f);
            //var scale = Matrix4x4.CreateScale(1.00f,1.00f,1.00f);


            string filePath = "models/chinesedragon.dae";
            // string filePath = "Models/Box.dae";
            var model = AssimpLoader.LoadFromFileWithRealtimeMaterial <VertexPositionNormal>(AppContext.BaseDirectory, filePath, VertexPositionNormal.HenzaiType);
            var newModelTranslation = Matrix4x4.CreateTranslation(new Vector3(0, 20, 0));
            var modelRuntimeState
                = new ModelRuntimeDescriptor <VertexPositionNormal>(model, "PhongOmni", "PhongOmni", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            modelRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;
            model.SetNewWorldTransformation(ref newModelTranslation, true);


            //TODO: Write method to remove ambient terms
            var sponzaModels = AssimpLoader.LoadRealtimeModelsFromFile(AppContext.BaseDirectory, "sponza/sponza.obj");
            var sponzaPNTTB  = sponzaModels.modelPNTTB;
            var sponzaPC     = sponzaModels.modelPC;

            for (int i = 0; i < sponzaPNTTB.MaterialCount; i++)
            {
                sponzaPNTTB.GetMaterial(i).ambient = new Vector4(0.3f, 0.3f, 0.3f, 1.0f);
            }

            for (int i = 0; i < sponzaPC.MaterialCount; i++)
            {
                sponzaPC.GetMaterial(i).ambient = new Vector4(0.3f, 0.3f, 0.3f, 1.0f);
            }
            sponzaPNTTB.SetNewWorldTransformation(ref scale, true);
            sponzaPC.SetNewWorldTransformation(ref scale, true);

            var sponzaRuntimeState  //TOOD: Omni Fragment shader produces a runtime error
                = new ModelRuntimeDescriptor <VertexPositionNormalTextureTangentBitangent>(sponzaPNTTB, "PhongBitangentTextureOmni", "PhongBitangentTextureOmni", VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            sponzaRuntimeState.CallVertexLayoutGeneration          += ResourceGenerator.GenerateVertexLayoutForPNTTB;
            sponzaRuntimeState.CallSamplerGeneration               += ResourceGenerator.GenerateTriLinearSampler;
            sponzaRuntimeState.CallTextureResourceLayoutGeneration += ResourceGenerator.GenerateTextureResourceLayoutForNormalMapping;
            sponzaRuntimeState.CallTextureResourceSetGeneration    += ResourceGenerator.GenerateTextureResourceSetForNormalMapping;


            var sponzaRuntimeStateColorOnly = new ModelRuntimeDescriptor <VertexPositionColor>(sponzaPC, "Color", "Color", VertexRuntimeTypes.VertexPositionColor, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            sponzaRuntimeStateColorOnly.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPC;

            ///

            var floor             = new Model <VertexPositionNormalTextureTangentBitangent, RealtimeMaterial>("paving/", GeometryFactory.GenerateQuadPNTTB_XY(), new RealtimeMaterial());
            var floorMeshZero     = floor.GetMesh(0);
            var flootMaterialZero = floor.GetMaterial(0);

            flootMaterialZero.textureDiffuse = "pavingColor.jpg";
            flootMaterialZero.textureNormal  = "pavingNorm.jpg";
            flootMaterialZero.ambient        = new Vector4(0.3f, 0.3f, 0.3f, 1.0f);
            var floorTranslation = Matrix4x4.CreateTranslation(-6, 0, -7);
            var floorScale       = Matrix4x4.CreateScale(100.0f, 100.0f, 1);
            var newTrans         = Matrix4x4.Multiply(floorScale, floorTranslation);

            floor.SetNewWorldTransformation(ref floorTranslation, true);
            var floorRuntimeState = new ModelRuntimeDescriptor <VertexPositionNormalTextureTangentBitangent>(floor, "PhongBitangentTextureOmni", "PhongBitangentTextureOmni", VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent, PrimitiveTopology.TriangleStrip, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            floorRuntimeState.CallVertexLayoutGeneration          += ResourceGenerator.GenerateVertexLayoutForPNTTB;
            floorRuntimeState.CallTextureResourceLayoutGeneration += ResourceGenerator.GenerateTextureResourceLayoutForNormalMapping;
            floorRuntimeState.CallTextureResourceSetGeneration    += ResourceGenerator.GenerateTextureResourceSetForNormalMapping;
            floorRuntimeState.CallSamplerGeneration += ResourceGenerator.GenerateTriLinearSampler;


            /////
            var floor2             = new Model <VertexPositionNormalTextureTangentBitangent, RealtimeMaterial>("paving/", GeometryFactory.GenerateQuadPNTTB_XZ(), new RealtimeMaterial());
            var floorMeshZero2     = floor2.GetMesh(0);
            var flootMaterialZero2 = floor2.GetMaterial(0);

            flootMaterialZero2.textureDiffuse = "pavingColor.jpg";
            flootMaterialZero2.textureNormal  = "pavingNorm.jpg";
            flootMaterialZero2.ambient        = new Vector4(0.3f, 0.3f, 0.3f, 1.0f);
            var floorTranslation2 = Matrix4x4.CreateTranslation(0, -5, 0);
            var floorScale2       = Matrix4x4.CreateScale(100.0f, 1.0f, 100.0f);
            var newTrans2         = Matrix4x4.Multiply(floorScale2, floorTranslation2);

            floor2.SetNewWorldTransformation(ref newTrans2, true);
            var floorRuntimeState2 = new ModelRuntimeDescriptor <VertexPositionNormalTextureTangentBitangent>(floor2, "PhongBitangentTextureOmni", "PhongBitangentTextureOmni", VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent, PrimitiveTopology.TriangleStrip, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            floorRuntimeState2.CallVertexLayoutGeneration          += ResourceGenerator.GenerateVertexLayoutForPNTTB;
            floorRuntimeState2.CallTextureResourceLayoutGeneration += ResourceGenerator.GenerateTextureResourceLayoutForNormalMapping;
            floorRuntimeState2.CallTextureResourceSetGeneration    += ResourceGenerator.GenerateTextureResourceSetForNormalMapping;
            floorRuntimeState2.CallSamplerGeneration += ResourceGenerator.GenerateTriLinearSampler;

            //



            var skyBox         = new Model <VertexPosition, RealtimeMaterial>("cloudtop", GeometryFactory.GenerateCube(true), new RealtimeMaterial());
            var skyBoxMaterial = skyBox.GetMaterial(0);

            skyBoxMaterial.AssignCubemapPaths("cloudtop_ft.png", "cloudtop_bk.png", "cloudtop_lf.png", "cloudtop_rt.png", "cloudtop_up.png", "cloudtop_dn.png");

            _skyBoxRuntimeState = new ModelRuntimeDescriptor <VertexPosition>(skyBox, "Skybox", "Skybox", VertexRuntimeTypes.VertexPosition, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));
            _skyBoxRuntimeState.CallVertexLayoutGeneration          += ResourceGenerator.GenerateVertexLayoutForP;
            _skyBoxRuntimeState.CallSamplerGeneration               += ResourceGenerator.GenerateBiLinearSampler;
            _skyBoxRuntimeState.CallTextureResourceLayoutGeneration += ResourceGenerator.GenerateTextureResourceLayoutForCubeMapping;
            _skyBoxRuntimeState.CallTextureResourceSetGeneration    += ResourceGenerator.GenerateTextureResourceSetForCubeMapping;

            _sun = new Model <VertexPositionNormal, RealtimeMaterial>(string.Empty, GeometryFactory.GenerateSphereNormal(100, 100, 0.3f), new RealtimeMaterial());
            _sun.GetMaterial(0).ambient = lightColor.ToVector4();
            Vector3 newTranslation = new Vector3(lightPos.X, lightPos.Y, lightPos.Z);

            _sun.SetNewWorldTranslation(ref newTranslation, true);

            var sunRuntimeState = new ModelRuntimeDescriptor <VertexPositionNormal>(_sun, "PhongNoShadow", "PhongNoShadow", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            sunRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;

            var _sun2 = new Model <VertexPositionNormal, RealtimeMaterial>(string.Empty, GeometryFactory.GenerateSphereNormal(100, 100, 0.5f), new RealtimeMaterial());

            _sun2.GetMaterial(0).ambient = lightColor.ToVector4();
            Vector3 newTranslation2 = new Vector3(5, -2, 1);

            _sun2.SetNewWorldTranslation(ref newTranslation2, true);

            var sunRuntimeState2 = new ModelRuntimeDescriptor <VertexPositionNormal>(_sun2, "PhongOmni", "PhongOmni", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            sunRuntimeState2.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;

            var _sun3 = new Model <VertexPositionNormal, RealtimeMaterial>(string.Empty, GeometryFactory.GenerateSphereNormal(100, 100, 0.5f), new RealtimeMaterial());

            _sun3.GetMaterial(0).ambient = lightColor.ToVector4();
            Vector3 newTranslation3 = new Vector3(-5, 0, -3.0f);

            _sun3.SetNewWorldTranslation(ref newTranslation3, true);

            var sunRuntimeState3 = new ModelRuntimeDescriptor <VertexPositionNormal>(_sun3, "PhongOmni", "PhongOmni", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            sunRuntimeState3.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;

            var _sun4 = new Model <VertexPositionNormal, RealtimeMaterial>(string.Empty, GeometryFactory.GenerateSphereNormal(100, 100, 0.2f), new RealtimeMaterial());

            _sun4.GetMaterial(0).ambient = lightColor.ToVector4();
            Vector3 newTranslation4 = new Vector3(0, -2, 0.0f);

            _sun4.SetNewWorldTranslation(ref newTranslation4, true);

            var sunRuntimeState4 = new ModelRuntimeDescriptor <VertexPositionNormal>(_sun4, "PhongOmni", "PhongOmni", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.OMNI_SHADOW_MAPS), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            sunRuntimeState4.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;



            //TODO: Automate this
            //_modelPNTTBDescriptorList.Add(sponzaRuntimeState);
            _modelPNTTBDescriptorList.Add(floorRuntimeState);
            //Rendering this seems to crate aretfacts on the other floor
            _modelPNTTBDescriptorList.Add(floorRuntimeState2);
            //_modelPCDescriptorList.Add(sponzaRuntimeStateColorOnly);
            //_modelPDescriptorList.Add(_skyBoxRuntimeState);

            _modelPNDescriptorList.Add(sunRuntimeState3);
            _modelPNDescriptorList.Add(sunRuntimeState);

            _modelPNDescriptorList.Add(sunRuntimeState2);
            _modelPNDescriptorList.Add(sunRuntimeState4);

            //_modelPNDescriptorList.Add(modelRuntimeState);


            InstanceData[] instancingData = { InstanceData.NO_DATA };

            //TODO: Abstrct this
            foreach (var modelDescriptor in _modelPNTTBDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingData);
                PNTTBRuntimeGeometry.AddModel(modelDescriptor);
            }

            foreach (var modelDescriptor in _modelPNDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingData);
                PNRuntimeGeometry.AddModel(modelDescriptor);
            }

            foreach (var modelDescriptor in _modelPTDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingData);
                PTRuntimeGeometry.AddModel(modelDescriptor);
            }

            foreach (var modelDescriptor in _modelPCDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingData);
                PCRuntimeGeometry.AddModel(modelDescriptor);
            }

            foreach (var modelDescriptor in _modelPDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingData);
                PRuntimeGeometry.AddModel(modelDescriptor);
            }
        }