public AssimpWpfImporterSample()
        {
            InitializeComponent();


            // Use helper class (defined in this sample project) to load the native assimp libraries.
            // IMPORTANT: See commend in the AssimpLoader class for details on how to prepare your project to use assimp library.
            AssimpLoader.LoadAssimpNativeLibrary();


            var assimpWpfImporter = new AssimpWpfImporter();

            string[] supportedImportFormats = assimpWpfImporter.SupportedImportFormats;

            var assimpWpfExporter = new AssimpWpfExporter();

            string[] supportedExportFormats = assimpWpfExporter.ExportFormatDescriptions.Select(f => f.FileExtension).ToArray();

            FileFormatsTextBlock.Text = string.Format("Using native Assimp library version {0}.\r\n\r\nSupported import formats:\r\n{1}\r\n\r\nSupported export formats:\r\n{2}",
                                                      assimpWpfImporter.AssimpVersion,
                                                      string.Join(", ", supportedImportFormats),
                                                      string.Join(", ", supportedExportFormats));


            var dragAndDropHelper = new DragAndDropHelper(this, ".*");

            dragAndDropHelper.FileDropped += (sender, args) => LoadModel(args.FileName);


            string startUpFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Collada\duck.dae");

            LoadModel(startUpFileName);
        }
        public PBRRobotModel()
        {
            InitializeComponent();

            _disposables = new DisposeList();

            AssimpLoader.LoadAssimpNativeLibrary();

            _dxMaterials   = new Dictionary <AssimpMaterial, PhysicallyBasedMaterial>();
            _texturesCache = new Dictionary <string, ShaderResourceView>();

            _textureFiles = new Dictionary <TextureMapTypes, string>();

            // Load scene when we have the DXDevice ready
            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs args)
            {
                if (MainDXViewportView.DXScene == null) // Probably WPF 3D rendering
                {
                    return;
                }

                _rootFolder = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"Resources\RobotModel\");

                LoadRobotPart(RobotParts.Main);
                LoadRobotPart(RobotParts.Claw);
            };



            UpdateLights();

            this.Unloaded += delegate(object sender, RoutedEventArgs args) { Dispose(); };
        }
        public SkeletalAnimation()
        {
            InitializeComponent();

            // Use helper class (defined in this sample project) to load the native assimp libraries
            // IMPORTANT: See commend in the AssimpLoader class for details on how to prepare your project to use assimp library.
            AssimpLoader.LoadAssimpNativeLibrary();

            string fileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\soldier.X");

            LoadFileWithSkinnedAnimation(fileName);

            var dragAndDropHelper = new DragAndDropHelper(ViewportBorder, ".*");

            dragAndDropHelper.FileDropped += (sender, e) =>
            {
                LoadFileWithSkinnedAnimation(e.FileName);
            };

            // Stop the animation when user leaves this sample.
            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                if (_assimpAnimationController != null)
                {
                    _assimpAnimationController.StopAnimation();
                    _assimpAnimationController = null;
                }
            };
        }
Example #4
0
        private void AddHouseWithTreesModel()
        {
            // Use assimp importer to load house with trees.3DS
            AssimpLoader.LoadAssimpNativeLibrary();

            var assimpWpfImporter   = new AssimpWpfImporter();
            var houseWithTreesModel = (Model3DGroup)assimpWpfImporter.ReadModel3D(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Models\house with trees.3DS"));

            // Add AmbientLight
            var ambientLight = new AmbientLight(Color.FromRgb(80, 80, 80));

            houseWithTreesModel.Children.Add(ambientLight);

            // Show the loaded 3d scene
            var modelVisual3D = houseWithTreesModel.CreateModelVisual3D();

            _masterDXViewportView.Viewport3D.Children.Add(modelVisual3D);

            // Save the man01 model for animation (when clicked on "Change scene" button)
            _animatedPersonModel = assimpWpfImporter.NamedObjects["man01"] as Model3DGroup;


            // Add base green plate and the house models to a CustomRenderingQueue.
            // This is done with setting value of CustomRenderingQueue (custom DXAttribute) on some parts of the 3D scene.
            // This will add the specified models to the custom rendering queue (created in the OnMasterDXSceneCreated method).
            var modelNames = new string[] { "Box01", "Box02", "roof01" };

            foreach (var modelName in modelNames)
            {
                var model3D = assimpWpfImporter.NamedObjects[modelName] as Model3D;

                // Note that CustomRenderingQueue can be set to an instance of RenderingQueue or to a name (as string) of the RenderingQueue
                model3D.SetDXAttribute(DXAttributeType.CustomRenderingQueue, "CustomRenderingQueue");
            }
        }
Example #5
0
        public AssimpModelVisual3D()
        {
            // Use helper class (defined in this sample project) to load the native assimp libraries
            // IMPORTANT: See commend in the AssimpLoader class for details on how to prepare your project to use assimp library.
            AssimpLoader.LoadAssimpNativeLibrary();

            InitializeComponent();
        }
Example #6
0
        public DynamicEdgeLinesSample()
        {
            InitializeComponent();

            AssimpLoader.LoadAssimpNativeLibrary();

            LoadRobotArm();

            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                Ab3d.Utilities.CompositionRenderingHelper.Instance.Unsubscribe(this);
            };
        }
        public PBRModelViewer()
        {
            InitializeComponent();

            _disposables = new DisposeList();

            AssimpLoader.LoadAssimpNativeLibrary();

            _dxMaterials   = new Dictionary <AssimpMaterial, PhysicallyBasedMaterial>();
            _texturesCache = new Dictionary <string, ShaderResourceView>();
            _textureFiles  = new Dictionary <TextureMapTypes, string>();

            // Support dragging .obj files to load the 3D models from obj file
            var dragAndDropHelper = new DragAndDropHelper(ViewportBorder, ".*");

            dragAndDropHelper.FileDroped += delegate(object sender, FileDropedEventArgs e)
            {
                FileNameTextBox.Text   = e.FileName;
                FolderPathTextBox.Text = System.IO.Path.GetDirectoryName(e.FileName);

                LoadFile(e.FileName, null);
            };

            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs args)
            {
                if (MainDXViewportView.DXScene == null) // Probably WPF 3D rendering
                {
                    return;
                }

                string rootFolder     = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"Resources\RobotModel\");
                string fileName       = rootFolder + @"Robot_Claw.FBX";
                string texturesFolder = rootFolder + @"Robot_Claw_Maps\";

                FileNameTextBox.Text   = fileName;
                FolderPathTextBox.Text = texturesFolder;

                LoadFile(fileName, texturesFolder);
                UpdateEnvironmentMap();
            };

            this.Loaded += delegate(object sender, RoutedEventArgs args)
            {
                UpdateLights();
            };

            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                Dispose();
            };
        }
        public StaticEdgeLinesCreationSample()
        {
            InitializeComponent();

            AssimpLoader.LoadAssimpNativeLibrary();

            var dragAndDropHelper = new DragAndDropHelper(this, ".*");

            dragAndDropHelper.FileDropped += (sender, args) => LoadModelWithEdgeLines(args.FileName);

            string startupFileName = AppDomain.CurrentDomain.BaseDirectory + @"Resources\ObjFiles\house with trees.obj";

            LoadModelWithEdgeLines(startupFileName);
        }
        public AssimpIntroPage()
        {
            InitializeComponent();

            // We create an instance of AssimpWpfImporter to read all supported file formats
            // and set that to the FileFormatsTextBlock

            // Use helper class (defined in this sample project) to load the native assimp libraries
            // IMPORTANT: See commend in the AssimpLoader class for details on how to prepare your project to use assimp library.
            AssimpLoader.LoadAssimpNativeLibrary();

            var assimpWpfImporter = new AssimpWpfImporter();

            string[] supportedImportFormats = assimpWpfImporter.SupportedImportFormats;
            FileFormatsTextBlock.Text = string.Join(", ", supportedImportFormats);
        }
Example #10
0
        public AdvancedEdgeLinesSample()
        {
            InitializeComponent();


            PowerToysFeaturesInfoControl.InfoText =
                @"With Ab3d.PowerToys library it is possible to show 3D lines (this is not possible when only WPF 3D is used). But the problem is that the geometry for 3D lines (2 triangles for each line) need to be generated on the CPU. Because 3D lines need to face the camera, the geometry needs to be regenerated on each camera change. This can slow the performance of the application when a lot of 3D lines need to be shown.

The Ab3d.PowerToys library can also generate edge lines based on the angle between triangles (if angle is bigger then the specified angle, then an edge line is created).";


            DXEngineFeaturesInfoControl.InfoText =
                @"Ab3d.DXEngine can use hardware acceleration to create the geometry for 3D lines in the geometry shader. This can render millions on 3D lines on a modern GPU.

What is more, as shown in this sample, the following additional features are available when using Ab3d.DXEngine:
1) It is possible to set line depth bias that moves the lines closer to the camera so that they are rendered on top of the 3D shape. This way the lines are not partially occluded by the 3D shape because they occupy the same 3D space. The depth bias processing is done in the vertex shader.

2) It is possible to render object's outlines. Here a technique is used that first renders the scene with black color and with expanded geometry. Then the scene is rendered normally on top of the black scene. For other techniques to render object outlines see the 'Object outlines rendering' sample.

3) To reduce anti-aliasing the WPF 3D can use multi-sampling (MSAA). With Ab3d.DXEngine it is possible to further reduce the aliasing and produce super-smooth 3D lines with using super-sampling (SSAA). This renders the scene to a higher resolution (4 times higher when 4xSSAA is used). Then the rendered image is down-sampled to the final resolution with using a smart filter. This can be combined with multi-sampling to produce much better results that using multi-sampling alone.";


            DepthBiasComboBox.ItemsSource  = PossibleEdgeLineDepthBiases;
            DepthBiasComboBox.SelectedItem = 0.05;


            AssimpLoader.LoadAssimpNativeLibrary();

            var dragAndDropHelper = new DragAndDropHelper(this, ".*");

            dragAndDropHelper.FileDropped += (sender, args) => LoadModelWithEdgeLines(args.FileName);


            CreateDXViewportView();


            var startupFileName = AppDomain.CurrentDomain.BaseDirectory + @"Resources\Models\planetary-gear.fbx";

            LoadModelWithEdgeLines(startupFileName);


            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                Dispose();
            };
        }
        private Model3D LoadModel3D()
        {
            AssimpLoader.LoadAssimpNativeLibrary();

            string fileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Models\robotarm-upper-part.3ds");

            var assimpWpfImporter = new AssimpWpfImporter();
            var robotModel3D      = assimpWpfImporter.ReadModel3D(fileName);

            // To get object names execute the following in Visual Studio Immediate window:
            // robotModel3D.DumpHierarchy();

            var hand2Group = assimpWpfImporter.NamedObjects["Hand2__Group"] as Model3DGroup;

            _originalModelAxisAngleRotation3D = new AxisAngleRotation3D(new Vector3D(0, 0, -1), 0);
            var rotateTransform3D = new RotateTransform3D(_originalModelAxisAngleRotation3D);

            Ab3d.Utilities.TransformationsHelper.AddTransformation(hand2Group, rotateTransform3D);


            // By default all objects cast shadow, so to prevent that we need to set the IsCastingShadow to false.
            // This can be done in two ways:
            //
            // 1) Set DXAttributeType.IsCastingShadow on GeometryModel3D
            //    (only GeometryModel3D support that attribute;
            //     this need to be set before the WpfGeometryModel3DNode object is created from GeometryModel3D)
            //
            // 2) After the WpfGeometryModel3DNode is created from GeometryModel3D,
            // then we can set the IsCastingShadow on that SceneNode object - see commented code below.
            //
            // When we change the value of IsCastingShadow, we also need to enable checking this property with
            // setting the PlanarShadowRenderingProvider.IsCheckingIsCastingShadow property to true.
            // By default this property is set to false so improve performance
            // (prevent using FilterObjectsFunction in RenderObjectsRenderingStep that render shadow).

            _teapotGeometryModel3D = assimpWpfImporter.NamedObjects["Teapot"] as GeometryModel3D;
            _teapotGeometryModel3D.SetDXAttribute(DXAttributeType.IsCastingShadow, false);

            // If we want to change the value of IsCastingShadow when the object is already shown,
            // we need to change that in the WpfGeometryModel3DNode - for example:
            //var teapotSceneNode = MainDXViewportView.GetSceneNodeForWpfObject(_teapotGeometryModel3D) as WpfGeometryModel3DNode; // we can get the teapotSceneNode in MainDXViewportView.DXSceneInitialized
            //if (teapotSceneNode != null)
            //    teapotSceneNode.IsCastingShadow = false;

            return(robotModel3D);
        }
        public AssimpWpfExporterSample()
        {
            InitializeComponent();

            AssimpWpfImporter.LoadAssimpNativeLibrary(AppDomain.CurrentDomain.BaseDirectory);


            var assimpWpfExporter = new AssimpWpfExporter();

            _exportFormatDescriptions = assimpWpfExporter.ExportFormatDescriptions;


            for (int i = 0; i < _exportFormatDescriptions.Length; i++)
            {
                var comboBoxItem = new ComboBoxItem()
                {
                    Content = string.Format("{0} (.{1})", _exportFormatDescriptions[i].Description, _exportFormatDescriptions[i].FileExtension),
                    Tag     = _exportFormatDescriptions[i].FormatId
                };

                ExportTypeComboBox.Items.Add(comboBoxItem);
            }


            ExportTypeComboBox.SelectedIndex = 0; // Use Collada file format by default
            _selectedExportFormatId          = _exportFormatDescriptions[ExportTypeComboBox.SelectedIndex].FormatId;


            // Use helper class (defined in this sample project) to load the native assimp libraries
            // IMPORTANT: See commend in the AssimpLoader class for details on how to prepare your project to use assimp library.
            AssimpLoader.LoadAssimpNativeLibrary();

            _assimpWpfImporter = new AssimpWpfImporter();
            _assimpWpfImporter.AssimpPostProcessSteps = PostProcessSteps.Triangulate;

            CreateTestScene();

            // Set initial output file name
            OutputFileName.Text = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "AssimpExport.dae");

            // Add drag and drop handler for all file extensions
            var dragAndDropHelper = new DragAndDropHelper(ViewportBorder, "*");

            dragAndDropHelper.FileDroped += (sender, e) => LoadModel(e.FileName);
        }
        private Model3D LoadModel()
        {
            AssimpLoader.LoadAssimpNativeLibrary();

            string fileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\robotarm-upper-part.3ds");

            var assimpWpfImporter = new AssimpWpfImporter();
            var robotModel3D      = assimpWpfImporter.ReadModel3D(fileName);

            var hand2Group = assimpWpfImporter.NamedObjects["Hand2__Group"] as Model3DGroup;

            _axisAngleRotation3D = new AxisAngleRotation3D(new Vector3D(0, 0, -1), 0);
            var rotateTransform3D = new RotateTransform3D(_axisAngleRotation3D);

            Ab3d.Utilities.TransformationsHelper.AddTransformation(hand2Group, rotateTransform3D);

            return(robotModel3D);
        }
Example #14
0
    void Start()
    {
        loader         = GetComponent <PdxLoader>();
        animationPanel = GetComponent <AnimationPanel>();
        assimpLoader   = GetComponent <AssimpLoader>();

        /*fbxExporter = GetComponent<FBXExporterForUnity>();
        *  fbxImporter = GetComponent<FBXImporterForUnity>();*/

        toggleShadows.isOn      = 1 == PlayerPrefs.GetInt("toggleshadows", 1);
        toggleAA.isOn           = 1 == PlayerPrefs.GetInt("toggleaa", 1);
        togglePlane.isOn        = 1 == PlayerPrefs.GetInt("toggleplane", 1);
        toggleLocators.isOn     = 1 == PlayerPrefs.GetInt("togglelocators", 1);
        toggleLocatorNames.isOn = 1 == PlayerPrefs.GetInt("togglelocatornames", 1);
        toggleBoneNames.isOn    = 1 == PlayerPrefs.GetInt("togglebonenames", 1);
        toggleBones.isOn        = 1 == PlayerPrefs.GetInt("togglebones", 1);

        showBones     = toggleBones.isOn;
        showBoneNames = toggleBoneNames.isOn;

        ToggleShadows();
        TooglePlane();
        ToggleAA();
        ToggleBoneNames();
        ToggleBones();
        ToggleLocatorNames();
        ToggleLocators();

        panelShaders.gameObject.SetActive(false);

        meshPath.text = animPath.text = fbxPath.text = "";
        saveAnimButton.interactable = saveMeshButton.interactable = saveFbxButton.interactable = false;

        bigStatus.gameObject.SetActive(false);

        attachButton.SetActive(false);
        snowSlider.gameObject.SetActive(false);
        shaderPanel.SetActive(false);
    }
Example #15
0
        override protected void CreateResources()
        {
            RgbaFloat lightColor = RgbaFloat.White;
            // RgbaFloat lightColor = RgbaFloat.LightGrey;
            var lightPos = new Vector4(0, 100, 0, 1);
            var lookAt   = new Vector4(0, 0, 0, 1) - new Vector4(0, 50, 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;

            // 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, "Phong", "Phong", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.SHADOW_MAP), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

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

            var plane = new Model <VertexPositionNormal, RealtimeMaterial>(String.Empty, GeometryFactory.GenerateQuadPN_XZ(), new RealtimeMaterial());
            var newPlaneTranslation = Matrix4x4.CreateTranslation(new Vector3(0, 10, 0));
            var newPlaneScale       = Matrix4x4.CreateScale(new Vector3(30, 1, 30));
            var trafo = newPlaneScale * newPlaneTranslation;

            plane.SetNewWorldTransformation(ref trafo, true);
            var planeRuntimeState = new ModelRuntimeDescriptor <VertexPositionNormal>(plane, "Phong", "Phong", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleStrip, new RenderDescription(RenderFlags.NORMAL | RenderFlags.SHADOW_MAP), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            planeRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;

            //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
                = new ModelRuntimeDescriptor <VertexPositionNormalTextureTangentBitangent>(sponzaPNTTB, "PhongBitangentTexture", "PhongBitangentTexture", VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.SHADOW_MAP), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

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

            // var sponzaRuntimeStateTexOnly = new ModelRuntimeDescriptor<VertexPositionTexture>(sponzaPT,"Texture","Texture", VertexTypes.VertexPositionTexture,PrimitiveTopology.TriangleList);
            // sponzaRuntimeStateTexOnly.CallVertexLayoutGeneration+=ResourceGenerator.GenerateVertexLayoutForPT;
            // sponzaRuntimeStateTexOnly.CallSamplerGeneration+=ResourceGenerator.GenerateTriLinearSampler;
            // sponzaRuntimeStateTexOnly.CallTextureResourceLayoutGeneration+=ResourceGenerator.GenerateTextureResourceLayoutForDiffuseMapping;
            // sponzaRuntimeStateTexOnly.CallTextureResourceSetGeneration+=ResourceGenerator.GenerateTextureResourceSetForDiffuseMapping;

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

            sponzaRuntimeStateColorOnly.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPC;

            // var sunRuntimeState = new ModelRuntimeState<VertexPositionNormalTextureTangentBitangent>(sun,"PhongBitangentTexture","PhongBitangentTexture");
            // sunRuntimeState.CallVertexLayoutGeneration+=ResourceGenerator.GenerateVertexLayoutForPNTTB;
            // sunRuntimeState.CallSamplerGeneration+=ResourceGenerator.GenerateLinearSampler;
            // sunRuntimeState.CallTextureResourceLayoutGeneration+=ResourceGenerator.GenerateTextureResourceLayoutForNormalMapping;
            // sunRuntimeState.CallTextureResourceSetGeneration+=ResourceGenerator.GenerateTextureResourceSetForNormalMapping;

            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, 1), new RealtimeMaterial());
            _sun.GetMaterial(0).ambient = lightColor.ToVector4();
            // _sun.meshes[0].TryGetMaterial().ambient = lightColor.ToVector4();
            Vector3 newTranslation = new Vector3(lightPos.X, lightPos.Y, lightPos.Z);

            _sun.SetNewWorldTranslation(ref newTranslation, true);

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

            sunRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;

            //TODO: Automate this
            _modelPNTTBDescriptorList.Add(sponzaRuntimeState);
            _modelPCDescriptorList.Add(sponzaRuntimeStateColorOnly);
            _modelPDescriptorList.Add(_skyBoxRuntimeState);
            // _modelPTDescriptorList.Add(sponzaRuntimeStateTexOnly);
            // _modelStatesList.Add(sunRuntimeState);
            _modelPNDescriptorList.Add(sunRuntimeState);
            _modelPNDescriptorList.Add(modelRuntimeState);
            //_modelPNDescriptorList.Add(planeRuntimeState);

            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);
            }
        }
Example #16
0
        override protected void CreateResources()
        {
            // RgbaFloat lightColor = RgbaFloat.Orange;
            RgbaFloat lightColor = RgbaFloat.LightGrey;
            var       lightPos   = new Vector4(10, 20, 0, 1);
            var       meshPos    = new Vector4(0, 0, 0, 1);
            var       lookAt     = meshPos - lightPos;
            //TODO: Position seems to be buggy
            var lightCam = new OrthographicCamera(50, 50, lightPos, lookAt);

            _sceneRuntimeState.Light     = new Light(lightCam, lightColor, 0.1f);
            _sceneRuntimeState.Camera    = Camera;
            _sceneRuntimeState.SpotLight = Light.NO_POINTLIGHT;

            // string filePath = Path.Combine(AppContext.BaseDirectory, "armor/armor.dae");
            // string filePath = Path.Combine(AppContext.BaseDirectory, "nanosuit/nanosuit.obj");
            _nanosuit = AssimpLoader.LoadFromFileWithRealtimeMaterial <VertexPositionNormalTextureTangentBitangent>(AppContext.BaseDirectory, "nanosuit/nanosuit.obj", VertexPositionNormalTextureTangentBitangent.HenzaiType);
            // _nanosuit.SetAmbientForAllMeshes(new Vector4(0.1f,0.1f,0.1f,1.0f));
            // _model = AssimpLoader.LoadFromFile<VertexPositionNormalTextureTangentBitangent>(AppContext.BaseDirectory,"sponza/sponza.obj",VertexPositionNormalTextureTangentBitangent.HenzaiType);
            GeometryUtils.GenerateTangentAndBitagentSpaceFor(_nanosuit);
            // GeometryUtils.CheckTBN(_model);
            // var sun = new Model<VertexPositionNormalTextureTangentBitangent>("water",GeometryFactory.generateSphereTangentBitangent(100,100,1));
            _sun = new Model <VertexPositionNormal, RealtimeMaterial>(string.Empty, GeometryFactory.GenerateSphereNormal(100, 100, 1), new RealtimeMaterial());
            var meshZero     = _sun.GetMesh(0);
            var materialZero = _sun.GetMaterial(0);

            materialZero.textureDiffuse = "Water.jpg";
            materialZero.textureNormal  = "WaterNorm.jpg";
            materialZero.ambient        = lightColor.ToVector4();
            // _sun.meshes[0].TryGetMaterial().ambient = lightColor.ToVector4();
            Vector3 newTranslation = new Vector3(lightPos.X, lightPos.Y, lightPos.Z);

            _sun.SetNewWorldTranslation(ref newTranslation, true);

            var nanoSuitRuntimeState
                = new ModelRuntimeDescriptor <VertexPositionNormalTextureTangentBitangent>(_nanosuit, "PhongBitangentTexture", "PhongBitangentTexture", VertexRuntimeTypes.VertexPositionNormalTextureTangentBitangent, PrimitiveTopology.TriangleList, new RenderDescription(RenderFlags.NORMAL | RenderFlags.SHADOW_MAP), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

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

            // var sunRuntimeState = new ModelRuntimeState<VertexPositionNormalTextureTangentBitangent>(sun,"PhongBitangentTexture","PhongBitangentTexture");
            // sunRuntimeState.CallVertexLayoutGeneration+=ResourceGenerator.GenerateVertexLayoutForPNTTB;
            // sunRuntimeState.CallSamplerGeneration+=ResourceGenerator.GenerateLinearSampler;
            // sunRuntimeState.CallTextureResourceLayoutGeneration+=ResourceGenerator.GenerateTextureResourceLayoutForNormalMapping;
            // sunRuntimeState.CallTextureResourceSetGeneration+=ResourceGenerator.GenerateTextureResourceSetForNormalMapping;

            // _modelStatesList.Add(sunRuntimeState);

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

            sunRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;

            var plane = new Model <VertexPositionNormal, RealtimeMaterial>(String.Empty, GeometryFactory.GenerateQuadPN_XZ(), new RealtimeMaterial());
            var newPlaneTranslation = Matrix4x4.CreateTranslation(new Vector3(0, 0, 0));
            var newPlaneScale       = Matrix4x4.CreateScale(new Vector3(100, 1, 100));
            var trafo = newPlaneScale * newPlaneTranslation;

            plane.SetNewWorldTransformation(ref trafo, true);
            var planeRuntimeState = new ModelRuntimeDescriptor <VertexPositionNormal>(plane, "Phong", "Phong", VertexRuntimeTypes.VertexPositionNormal, PrimitiveTopology.TriangleStrip, new RenderDescription(RenderFlags.NORMAL | RenderFlags.SHADOW_MAP), new InstancingRenderDescription(RenderFlags.NONE, InstancingDataFlags.EMPTY));

            planeRuntimeState.CallVertexLayoutGeneration += ResourceGenerator.GenerateVertexLayoutForPN;

            _modelPNTTBDescriptorList.Add(nanoSuitRuntimeState);

            _modelPNDescriptorList.Add(planeRuntimeState);
            _modelPNDescriptorList.Add(sunRuntimeState);


            InstanceData[] instancingData = { InstanceData.NO_DATA };

            foreach (var modelDescriptor in _modelPNTTBDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingData);
                PNTTBRuntimeGeometry.AddModel(modelDescriptor);
            }

            foreach (var modelDescriptor in _modelPNDescriptorList)
            {
                FillRuntimeDescriptor(modelDescriptor, _sceneRuntimeState, instancingData);
                PNRuntimeGeometry.AddModel(modelDescriptor);
            }
        }
Example #17
0
        // TODO: Abstract Resource Crreation for Uniforms, Vertex Layouts, Disposing
        override protected void CreateResources()
        {
            //string filePath = Path.Combine(AppContext.BaseDirectory, "Models/sphere.obj"); // huge
            //string filePath = Path.Combine(AppContext.BaseDirectory, "Models/sphere_centered.obj"); // no texture coordiantes
            string filePath = "armor/armor.dae";

            _model = AssimpLoader.LoadFromFileWithRealtimeMaterial <VertexPositionNormalTextureTangent>(AppContext.BaseDirectory, filePath, VertexPositionNormalTextureTangent.HenzaiType);
            //GeometryUtils.GenerateSphericalTextureCoordinatesFor(_model.meshes[0], UVMappingTypes.Spherical_Coordinates,true);
            GeometryUtils.GenerateTangentSpaceFor(_model);
            // _model = new Model<VertexPositionNormalTextureTangent>(GeometryFactory.generateSphere(100,100,1.0f));

            /// Uniform 1 - Camera
            _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(192, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            var resourceLayoutElementDescription = new ResourceLayoutElementDescription("projViewWorld", ResourceKind.UniformBuffer, ShaderStages.Vertex);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription };
            var resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions);

            BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer };
            _cameraResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription);
            var resourceSetDescription = new ResourceSetDescription(_cameraResourceLayout, bindableResources);

            _cameraResourceSet = _factory.CreateResourceSet(resourceSetDescription);

            // Uniform 2 - Material
            _materialBuffer = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            var resourceLayoutElementDescriptionMaterial = new ResourceLayoutElementDescription("material", ResourceKind.UniformBuffer, ShaderStages.Fragment);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsMaterial = { resourceLayoutElementDescriptionMaterial };
            var resourceLayoutDescriptionMaterial = new ResourceLayoutDescription(resourceLayoutElementDescriptionsMaterial);

            BindableResource[] bindableResourcesMaterial = new BindableResource[] { _materialBuffer };

            _materialResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionMaterial);
            var resourceSetDescriptionMaterial = new ResourceSetDescription(_materialResourceLayout, bindableResourcesMaterial);

            _materialResourceSet = _factory.CreateResourceSet(resourceSetDescriptionMaterial);

            // Uniform 3 - Light
            _lightBuffer = _factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));

            var resourceLayoutElementDescriptionLight = new ResourceLayoutElementDescription("light", ResourceKind.UniformBuffer, ShaderStages.Vertex);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsLight = { resourceLayoutElementDescriptionLight };
            var resourceLayoutDescriptionLight = new ResourceLayoutDescription(resourceLayoutElementDescriptionsLight);

            BindableResource[] bindableResourcesLight = new BindableResource[] { _lightBuffer };

            _lightResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionLight);
            var resourceSetDescriptionLight = new ResourceSetDescription(_lightResourceLayout, bindableResourcesLight);

            _lightResourceSet = _factory.CreateResourceSet(resourceSetDescriptionLight);

            for (int i = 0; i < _model.MeshCount; i++)
            {
                var          mesh = _model.GetMesh(i);
                DeviceBuffer vertexBuffer
                    = _factory.CreateBuffer(new BufferDescription(mesh.Vertices.LengthUnsigned() * VertexPositionNormalTextureTangent.SizeInBytes, BufferUsage.VertexBuffer));

                DeviceBuffer indexBuffer
                    = _factory.CreateBuffer(new BufferDescription(mesh.Indices.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer));


                _vertexBuffers.Add(vertexBuffer);
                _indexBuffers.Add(indexBuffer);

                GraphicsDevice.UpdateBuffer(vertexBuffer, 0, mesh.Vertices);
                GraphicsDevice.UpdateBuffer(indexBuffer, 0, mesh.Indices);
            }

            //Texture Samper
            // ImageSharpTexture diffuseTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "earth.jpg"));
            // ImageSharpTexture diffuseTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "Water.jpg"));
            ImageSharpTexture diffuseTexture           = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "armor", "diffuse.png"));
            Texture           sphereDiffuseTexture     = diffuseTexture.CreateDeviceTexture(GraphicsDevice, _factory);
            TextureView       sphereDiffuseTextureView = _factory.CreateTextureView(sphereDiffuseTexture);

            // ImageSharpTexture normalTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "WaterNorm.jpg"));
            ImageSharpTexture normalTexture           = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "armor", "normal.png"));
            Texture           sphereNormalTexture     = normalTexture.CreateDeviceTexture(GraphicsDevice, _factory);
            TextureView       sphereNormalTextureView = _factory.CreateTextureView(sphereNormalTexture);

            ResourceLayout textureLayout = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("DiffuseTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("DiffuseSampler", ResourceKind.Sampler, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("NormTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("NormSampler", ResourceKind.Sampler, ShaderStages.Fragment)
                    ));

            var sampler = _factory.CreateSampler(new SamplerDescription
            {
                AddressModeU      = SamplerAddressMode.Wrap,
                AddressModeV      = SamplerAddressMode.Wrap,
                AddressModeW      = SamplerAddressMode.Wrap,
                Filter            = SamplerFilter.MinLinear_MagLinear_MipLinear,
                LodBias           = 0,
                MinimumLod        = 0,
                MaximumLod        = uint.MaxValue,
                MaximumAnisotropy = 0,
            });

            _textureResourceSet = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                 textureLayout,
                                                                 sphereDiffuseTextureView,
                                                                 GraphicsDevice.LinearSampler,
                                                                 sphereNormalTextureView,
                                                                 sampler
                                                                 ));

            VertexLayoutDescription vertexLayout
                = new VertexLayoutDescription(
                      new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                      new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3),
                      new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                      new VertexElementDescription("Tangent", VertexElementSemantic.Normal, VertexElementFormat.Float3)
                      );

            _vertexShader   = IO.LoadShader("PhongTexture", ShaderStages.Vertex, GraphicsDevice);
            _fragmentShader = IO.LoadShader("PhongTexture", ShaderStages.Fragment, GraphicsDevice);

            GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription()
            {
                BlendState        = BlendStateDescription.SingleOverrideBlend,
                DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual,
                RasterizerState   = new RasterizerStateDescription(
                    cullMode: FaceCullMode.Back,
                    fillMode: PolygonFillMode.Solid,
                    frontFace: FrontFace.Clockwise,
                    depthClipEnabled: true,
                    scissorTestEnabled: false
                    ),
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                ResourceLayouts   = new ResourceLayout[] { _cameraResourceLayout, _lightResourceLayout, _materialResourceLayout, textureLayout },
                ShaderSet         = new ShaderSetDescription(
                    vertexLayouts: new VertexLayoutDescription[] { vertexLayout },
                    shaders: new Shader[] { _vertexShader, _fragmentShader }
                    ),
                Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription
            };

            _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription);
        }
Example #18
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);
            }
        }
Example #19
0
        public BasicWpf3dObjectsTutorial()
        {
            InitializeComponent();

            var mesh2 = new MeshGeometry3D()
            {
                Positions = new Point3DCollection(new[]
                {
                    new Point3D(5, 0, 5),
                    new Point3D(100, 0, 5),
                    new Point3D(100, 0, 50),
                    new Point3D(5, 0, 50)
                }),

                TriangleIndices = new Int32Collection(new[]
                {
                    0, 2, 1,
                    3, 2, 0
                })
            };

            var geometryModel2 = new GeometryModel3D()
            {
                Geometry     = mesh2,
                Material     = new DiffuseMaterial(Brushes.LightGreen),
                BackMaterial = new DiffuseMaterial(Brushes.Red),
            };

            var modelVisual2 = new ModelVisual3D()
            {
                Content = geometryModel2
            };

            //// Using CreateModelVisual3D extensiton method from Ab3d.PowerToys
            //var modelVisual2 = geometryModel2.CreateModelVisual3D();
            //Viewport2.Children.Add(modelVisual2);

            //// in one line:
            //Viewport2.Children.Add(geometryModel2.CreateModelVisual3D());

            Viewport2.Children.Add(modelVisual2);

            MeshInspector2.MeshGeometry3D = mesh2;

            // #############

            var mesh3 = new MeshGeometry3D()
            {
                Positions       = mesh2.Positions,
                TriangleIndices = new Int32Collection(new[]
                {
                    2, 0, 1, // changed from 0, 2, 1
                    3, 2, 0
                }),
                Normals = new Vector3DCollection(new [] { new Vector3D(0, 1, 0), new Vector3D(0, 1, 0), new Vector3D(0, 1, 0), new Vector3D(0, 1, 0) }) // We define Normals because the automatically generated normals are not correct because the two triangles are oriented differently and this produces zero length normals for the shared positions; note that for mesh2 this was not needed because triangles are correctly oriented and WPF was able to correctly calculate normals.
            };

            _geometryModel3 = new GeometryModel3D()
            {
                Geometry     = mesh3,
                Material     = new DiffuseMaterial(Brushes.LightGreen),
                BackMaterial = new DiffuseMaterial(Brushes.Red),
            };

            var modelVisual3 = new ModelVisual3D()
            {
                Content = _geometryModel3
            };

            Viewport3.Children.Add(modelVisual3);

            MeshInspector3.MeshGeometry3D = mesh3;

            // #############

            var modelVisual4 = new ModelVisual3D()
            {
                Content = _geometryModel3
            };

            Viewport4.Children.Add(modelVisual4);

            MeshInspector4.MeshGeometry3D = mesh3;

            // #############

            var mesh5 = new MeshGeometry3D()
            {
                Positions          = mesh2.Positions,
                TriangleIndices    = mesh2.TriangleIndices,
                TextureCoordinates = new PointCollection(new[]
                {
                    new Point(0, 0),
                    new Point(1, 0),
                    new Point(1, 1),
                    new Point(0, 1),
                })
            };

            var textureImage = new BitmapImage(new Uri("pack://*****:*****@"c:\images\texture.png")); // Read image from file
            //var textureImage2 = new BitmapImage(new Uri("pack://*****:*****@"Resources\robotarm-upper-part.3ds");

            var assimpWpfImporter = new AssimpWpfImporter();
            var robotModel3D      = assimpWpfImporter.ReadModel3D(fileName);

            string dumpString = Ab3d.Utilities.Dumper.GetObjectHierarchyString(robotModel3D);

            RobotArmSampleTextBox.Text = dumpString;


            //var transform3DGroup = new Transform3DGroup();
            //transform3DGroup.Children.Add(new ScaleTransform3D(2, 3, 2));
            //transform3DGroup.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), 45)));
            //transform3DGroup.Children.Add(new TranslateTransform3D(100, 0, 0));

            //geometryModel2.Transform = transform3DGroup;
        }
        public ObjectOutlinesRenderingSample()
        {
            InitializeComponent();


            OutlineThicknessComboBox.ItemsSource  = new float[] { 0f, 0.1f, 0.5f, 1f, 2f, 3f, 4f, 5f, 10f, 20f };
            OutlineThicknessComboBox.SelectedItem = 3.0f;

            OutlineDepthBiasComboBox.ItemsSource  = new float[] { 0f, 0.0001f, 0.0005f, 0.001f, 0.005f, 0.01f, 0.02f, 0.01f, 0.1f, 0.2f, 0.3f, 0.5f, 0.8f, 0.9f, 1f, 2f, 5f, 10f };
            OutlineDepthBiasComboBox.SelectedItem = 0.005f;

            EdgeThresholdComboBox.ItemsSource  = new float[] { 0f, 0.01f, 0.02f, 0.01f, 0.1f, 0.2f, 0.3f, 0.5f, 0.8f, 0.9f, 1f };
            EdgeThresholdComboBox.SelectedItem = 0.1f;

            OutlineWidthComboBox.ItemsSource  = new int[] { 1, 2, 3, 4, 5, 7, 10, 12, 16 };
            OutlineWidthComboBox.SelectedItem = 3;



            ShowObjectOutlineInfoControl.InfoText =
                @"A new RenderObjectsRenderingStep is created that renders all objects with SolidColorEffect with black color. The SolidColorEffect has the OutlineThickness property set and this expands the object's geometry in the direction of triangle normals (this is done in vertex shader). Then the scene is rendered again with standard effects on top of the black expanded scene.

To render outline around each object uncheck the 'Outline CullNone' and 'WriteMaxDepthValue' CheckBoxes. But on simpler objects with less triangles this may not render outlines in all directions.

To render silhouette around the whole 3D scene and not around each object, then check the 'Outline CullNone' and 'WriteMaxDepthValue' CheckBoxes. The first CheckBox will render back and front triangles. The second will render the objects to the back of the 3D scene (after all other objects).

This technique works well on objects that have a lot of smooth shaded positions and do not have sharp edges with big angles - for example rendering box with bigger OutlineThickness can show that the black sides are rendered away from the actual 3D object.
When 3D scene has many 3D objects, then using the technique can affect performance because the scene needs to be rendered 2 times (once for black background and once for standard rendering). This technique works with multi-sampling and super-sampling.";


            ExpandPostProcessInfoControl.InfoText =
                @"This technique is similar than the previous technique because it also first renders the scene with a black SolidColorEffect. But instead of expanding the object's geometry, the scene is rendered normally with black color. Then an ExpandPostProcess is used to expand the rendered black scene for the specified amount.

This technique can produce more accurate results then using SolidColorEffect with OutlineThickness (especially for objects with sharp edges). But it is the slowest because it requires to render the scene again and then perform a two pass post-processing. This technique is not support when multi-sampling is used.";


            EdgeDetectionPostProcessInfoControl.InfoText =
                @"EdgeDetectionPostProcess is a 2D texture post process that uses Sobel edge detection algorithm to detect edges based on the changes of color in the rendered 3D scene - if colors are different enough then a black edge is added to the rendered image.

If the rendered scene has many 3D objects, then this algorithm is the fastest because it does not require to render the 3D scene again. This technique does not support multi-sampling and super-sampling (executed after back-buffer is resolved).";



            AssimpLoader.LoadAssimpNativeLibrary();

            var dragAndDropHelper = new DragAndDropHelper(this, ".*");

            dragAndDropHelper.FileDropped += (sender, args) => LoadModel(args.FileName);

            string startupFileName = AppDomain.CurrentDomain.BaseDirectory + @"Resources\Models\house with trees.3ds";

            LoadModel(startupFileName);


            _disposables = new DisposeList();

            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs args)
            {
                // Wait until DXScene is created and then setup custom rendering steps to render outlines
                if (MainDXViewportView.DXScene == null)
                {
                    return;                                                            // WPF 3D rendering
                }
                if (MainDXViewportView.DXScene.UsedMultisamplingDescription.Count > 1) // Expand post process is available only without multi-sampling (MSAA)
                {
                    ExpandPostProcessCheckBox.IsChecked = false;
                    ExpandPostProcessCheckBox.IsEnabled = false;
                    OutlineWidthComboBox.IsEnabled      = false;

                    ExpandNotSupportedTextBlock.Visibility = Visibility.Visible;
                }

                UpdateUsedOutlineTechnique();
            };

            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                if (_disposables != null)
                {
                    _disposables.Dispose();
                    _disposables = null;
                }

                MainDXViewportView.Dispose();
            };
        }
Example #21
0
        // TODO: Abstract Resource Crreation for Uniforms, Vertex Layouts, Disposing
        override protected void CreateResources()
        {
            RgbaFloat lightColor  = RgbaFloat.LightGrey;
            var       lightLookAt = new Vector4(0, 0, 0, 1);
            var       lightCam    = new OrthographicCamera(35, 35, Light.DEFAULT_POSITION, lightLookAt);

            _sceneRuntimeState.Light = new Light(lightCam, lightColor, 0.1f);
            // string filePath = Path.Combine(AppContext.BaseDirectory, "Models/sphere.obj");
            //string filePath = Path.Combine(AppContext.BaseDirectory, "Models/300_polygon_sphere_100mm.STL");
            // string filePath =  "Models/sphere_centered.obj";
            string filePath = "Models/chinesedragon.dae";

            // string filePath = "Models/Box.dae";
            _model = AssimpLoader.LoadFromFileWithRealtimeMaterial <VertexPositionNormal>(AppContext.BaseDirectory, filePath, VertexPositionNormal.HenzaiType);
            //GeometryUtils.GenerateSphericalTextureCoordinatesFor(_model.meshes[0]);

            /// Uniform 1 - Camera
            _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(Camera.SizeInBytes, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            var resourceLayoutElementDescription = new ResourceLayoutElementDescription("projViewWorld", ResourceKind.UniformBuffer, ShaderStages.Vertex);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription };
            var resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions);

            BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer };

            _cameraResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription);
            var resourceSetDescription = new ResourceSetDescription(_cameraResourceLayout, bindableResources);

            _cameraResourceSet = _factory.CreateResourceSet(resourceSetDescription);

            // Uniform 2 - Material
            _materialBuffer = _factory.CreateBuffer(new BufferDescription(RealtimeMaterial.SizeInBytes, BufferUsage.UniformBuffer));

            var resourceLayoutElementDescriptionMaterial = new ResourceLayoutElementDescription("material", ResourceKind.UniformBuffer, ShaderStages.Fragment);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsMaterial = { resourceLayoutElementDescriptionMaterial };
            var resourceLayoutDescriptionMaterial = new ResourceLayoutDescription(resourceLayoutElementDescriptionsMaterial);

            BindableResource[] bindableResourcesMaterial = new BindableResource[] { _materialBuffer };

            _materialResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionMaterial);
            var resourceSetDescriptionMaterial = new ResourceSetDescription(_materialResourceLayout, bindableResourcesMaterial);

            _materialResourceSet = _factory.CreateResourceSet(resourceSetDescriptionMaterial);

            // Uniform 3 - Light
            _lightBuffer = _factory.CreateBuffer(new BufferDescription(Light.SizeInBytes, BufferUsage.UniformBuffer));

            var resourceLayoutElementDescriptionLight = new ResourceLayoutElementDescription("light", ResourceKind.UniformBuffer, ShaderStages.Fragment);

            ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsLight = { resourceLayoutElementDescriptionLight };
            var resourceLayoutDescriptionLight = new ResourceLayoutDescription(resourceLayoutElementDescriptionsLight);

            BindableResource[] bindableResourcesLight = new BindableResource[] { _lightBuffer };

            _lightResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionLight);
            var resourceSetDescriptionLight = new ResourceSetDescription(_lightResourceLayout, bindableResourcesLight);

            _lightResourceSet = _factory.CreateResourceSet(resourceSetDescriptionLight);

            for (int i = 0; i < _model.MeshCount; i++)
            {
                var          mesh = _model.GetMesh(i);
                DeviceBuffer vertexBuffer
                    = _factory.CreateBuffer(new BufferDescription(mesh.Vertices.LengthUnsigned() * VertexPositionNormal.SizeInBytes, BufferUsage.VertexBuffer));

                DeviceBuffer indexBuffer
                    = _factory.CreateBuffer(new BufferDescription(mesh.Indices.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer));


                _vertexBuffers.Add(vertexBuffer);
                _indexBuffers.Add(indexBuffer);

                GraphicsDevice.UpdateBuffer(vertexBuffer, 0, mesh.Vertices);
                GraphicsDevice.UpdateBuffer(indexBuffer, 0, mesh.Indices);
            }

            VertexLayoutDescription vertexLayout
                = new VertexLayoutDescription(
                      new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                      new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3)
                      //new VertexElementDescription("UV",VertexElementSemantic.TextureCoordinate,VertexElementFormat.Float2)
                      );

            _vertexShader   = IO.LoadShader("Phong", ShaderStages.Vertex, GraphicsDevice);
            _fragmentShader = IO.LoadShader("Phong", ShaderStages.Fragment, GraphicsDevice);

            GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription()
            {
                BlendState        = BlendStateDescription.SingleOverrideBlend,
                DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual,
                RasterizerState   = new RasterizerStateDescription(
                    cullMode: FaceCullMode.Back,
                    fillMode: PolygonFillMode.Solid, // Wireframe doesnt seem to work with metal
                    frontFace: FrontFace.Clockwise,
                    depthClipEnabled: true,
                    scissorTestEnabled: false
                    ),
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                //ResourceLayouts = new ResourceLayout[] {_cameraResourceLayout,_materialResourceLayout,_lightResourceLayout},
                ResourceLayouts = new ResourceLayout[] { _cameraResourceLayout, _lightResourceLayout, _materialResourceLayout },
                ShaderSet       = new ShaderSetDescription(
                    vertexLayouts: new VertexLayoutDescription[] { vertexLayout },
                    shaders: new Shader[] { _vertexShader, _fragmentShader }
                    ),
                Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription
            };

            _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription);
        }
Example #22
0
        public static void OpenAndConvertAssimpFiles()
        {
            var files = GetInputFiles()
                        .Where(AssimpLoader.CanLoad)
                        .Select(f => new FileLoadData(f))
                        .ToArray();

            // Load all the files
            foreach (var f in files)
            {
                try
                {
                    (f.MemoryConsumption, f.MSecToOpen) =
                        Util.GetMemoryConsumptionAndMSecElapsed(() =>
                                                                f.Scene = AssimpLoader.Load(f.SourceFile.FullName));
                }
                catch (Exception e)
                {
                    f.Error = e;
                }
            }

            // Convert all the Assimp scenes to G3D
            foreach (var f in files)
            {
                if (f.Scene == null)
                {
                    continue;
                }

                try
                {
                    f.MSecToConvert = Util.GetMSecElapsed(() =>
                                                          f.G3d = f.Scene.ToG3d());
                }
                catch (Exception e)
                {
                    f.Error = e;
                }
            }

            // Save all the G3D scenes
            Util.CreateAndClearDirectory(TestOutputFolder);
            foreach (var f in files)
            {
                if (f.G3d == null)
                {
                    continue;
                }

                try
                {
                    var outputFilePath = Path.Combine(TestOutputFolder, f.ShortName + ".g3d");
                    f.G3DFile = new FileInfo(outputFilePath);

                    f.MSecToSaveG3d = Util.GetMSecElapsed(() =>
                                                          f.G3d.Write(outputFilePath));
                }
                catch (Exception e)
                {
                    f.Error = e;
                }
            }

            // Try reading back in all of the G3D scenes, measure load times and the memory consumption
            foreach (var f in files)
            {
                if (f.G3DFile == null)
                {
                    continue;
                }

                try
                {
                    G3D localG3d = null;

                    (f.MemoryConsumptionG3d, f.MSecToOpenG3d) =
                        Util.GetMemoryConsumptionAndMSecElapsed(() =>
                                                                localG3d = G3D.Read(f.G3DFile.FullName));

                    ValidateSameG3D(f.G3d, localG3d);
                }
                catch (Exception e)
                {
                    f.Error = e;
                }
            }

            // Output the header for data
            Console.WriteLine(
                "Importer," +
                "Extension," +
                "File Name," +
                "File Size(KB)," +
                "Load Time(s)," +
                "Memory(KB)," +
                "# Meshes," +
                "Time to Convert," +
                "Time to Write G3D," +
                "G3D File Size(KB)," +
                "G3D Memory(KB)",
                "G3D Load Time(s)",
                "Error");

            // Output the data rows
            foreach (var f in files)
            {
                Console.WriteLine(
                    "Assimp," +
                    $"{Path.GetExtension(f.ShortName)}," +
                    $"{f.ShortName}," +
                    $"{f.SourceFile?.Length / 1000}," +
                    $"{f.MSecToOpen / 100f}," +
                    $"{f.MemoryConsumption / 1000}," +
                    $"{f.NumMeshes}," +
                    $"{f.MSecToConvert / 100f}," +
                    $"{f.MSecToSaveG3d / 100f}," +
                    $"{f.G3DFile?.Length / 1000}," +
                    $"{f.MemoryConsumptionG3d / 1000}," +
                    $"{f.MSecToOpenG3d / 100f}," +
                    $"{f.Error}");
            }

            Assert.AreEqual(0, files.Count(f => f.Error != null), "Errors occurred");
        }