Ejemplo n.º 1
0
        private void DigitalRuneAdaptorScene()
        {
            //creating the simulation
            CreateScene();

            //definig a material
            var materialDesc = new MaterialDescription
                                   {
                                       DynamicFriction = 0.5f,
                                       StaticFriction = 0.5f,
                                       Restitution = 0.7f,
                                       FrictionCombineMode = CombineMode.Average,
                                       RestitutionCombineMode = CombineMode.Average
                                   };
            Nx.Material material = _scene.CreateMaterial(materialDesc);

            //creating the ground
            CreateGround(material);

            ////creating a Tower

            CreateTower(material, new NxVector3(1, 1, 1),
                        xCount: 5, yCount: 5, zCount: 5,
                        xSpace: 2, ySpace: 2, zSpace: 2,
                        xOffset: 0, yOffset: 2 + 10 / 2, zOffset: 0);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TriangleMeshObject"/> class.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="pos">The pos.</param>
        /// <param name="rotation">The rotation.</param>
        /// <param name="scale">The scale.</param>
        /// <param name="materialDescription">The material description.</param>
        public TriangleMeshObject(IModelo model, Vector3 pos, Matrix? rotation = null, Vector3? scale= null, MaterialDescription materialDescription = null)
        {
            if (materialDescription == null)
                materialDescription = MaterialDescription.DefaultBepuMaterial();

            if (!rotation.HasValue)
                rotation = Matrix.Identity;

            if (!scale.HasValue)
                scale = Vector3.One;

            System.Diagnostics.Debug.Assert(model != null);
            System.Diagnostics.Debug.Assert(scale != Vector3.Zero);

            this.rotation = rotation.Value;
            this.scale = scale.Value;
            this.position = pos;
            Vector3[] vertices = null;
            int[] indices = null;
            ExtractData(ref vertices, ref indices, model);
            triangleGroup = new StaticMesh(vertices, indices, new AffineTransform(scale.Value, Quaternion.CreateFromRotationMatrix(rotation.Value), position));
            faceVector = Vector3.Transform(Vector3.Forward, triangleGroup.WorldTransform.Matrix);
            triangleGroup.Material = new BEPUphysics.Materials.Material(materialDescription.StaticFriction, materialDescription.DynamicFriction, materialDescription.Bounciness);
            
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SphereObject"/> class.
 /// </summary>
 /// <param name="pos">The pos.</param>
 /// <param name="raio">The raio.</param>
 /// <param name="mass">The mass.</param>
 /// <param name="scale">The scale.</param>
 /// <param name="materialDescription">The material description.</param>
 public SphereObject(Vector3 pos, float raio, float mass = 10,float scale = 1,MaterialDescription materialDescription = null)
     : base(materialDescription,mass)
 {
 
     this.scale = new Vector3(scale);
     entity = new Sphere(pos, raio * scale, mass);            
 }
Ejemplo n.º 4
0
        protected void iniPhysx(Vector3 startPosition)
        {
            BodyDescription boxBody = new BodyDescription();
            boxBody.AngularVelocity = new StillDesign.PhysX.MathPrimitives.Vector3(1, 0, 0);
            boxBody.Mass = 2000;

            //Material
            MaterialDescription materialDesc = new MaterialDescription();
            materialDesc.Restitution = 0.001f;
            materialDesc.StaticFriction = 0.5f;
            materialDesc.DynamicFriction = 0.5f;
            materialDesc.Name = "Test";
            this.game.scene.CreateMaterial(materialDesc);

            BoxShapeDescription boxShapeDesc = new BoxShapeDescription();
            boxShapeDesc.Dimensions = new StillDesign.PhysX.MathPrimitives.Vector3(20.5f, 6.4f, 34.0f);
            boxShapeDesc.Material = this.game.scene.Materials[1];
            boxShapeDesc.Mass = 2000;

            ActorDescription actor = new ActorDescription();

            actor.GlobalPose = StillDesign.PhysX.MathPrimitives.Matrix.Translation(startPosition.X, startPosition.Y, startPosition.Z);
            actor.BodyDescription = boxBody;
            actor.Shapes.Add(boxShapeDesc);

            this.actor = this.game.scene.CreateActor(actor);
            this.shape = this.actor.CreateShape(boxShapeDesc) as BoxShape;
        }
Ejemplo n.º 5
0
        public MaterialDescription Run(MaterialDescription material, UDirectory materialPath, PixelFormat outputFormat = PixelFormat.ETC1)
        {
            if (material == null) throw new ArgumentNullException("material");

            var assetManager = new AssetManager();
            var modifiedMaterial = material.Clone();
            var textureVisitor = new MaterialTextureVisitor(modifiedMaterial);
            var nodeReplacer = new MaterialNodeReplacer(modifiedMaterial);
            var textureNodes = textureVisitor.GetAllModelTextureValues();

            foreach (var textureNode in textureNodes)
            {
                var itemAsset = assetSession.FindAsset(textureNode.TextureReference.Id);
                if(itemAsset == null)
                    throw new InvalidOperationException("The referenced texture is not included in the project session.");

                var textureAsset = (TextureAsset)itemAsset.Asset;
                if (textureAsset.Format != TextureFormat.Compressed || textureAsset.Alpha == AlphaFormat.None)
                    continue; // the texture has no alpha so there is no need to divide the texture into two sub-textures

                var originalLocation = textureNode.TextureReference.Location;

                throw new NotImplementedException("TODO: Need to reimplement this with removed data layer.");
                using (var image = assetManager.Load<Image>(originalLocation))
                {
                    CreateAndSaveSeparateTextures(image, originalLocation, textureAsset.GenerateMipmaps, outputFormat);
                    assetManager.Unload(image); // matching unload to the previous asset manager load call
                }

                // make new tree
                var colorNode = new MaterialTextureNode(GenerateColorTextureURL(originalLocation), textureNode.TexcoordIndex, Vector2.One, Vector2.Zero);
                var alphaNode = new MaterialTextureNode(GenerateAlphaTextureURL(originalLocation), textureNode.TexcoordIndex, Vector2.One, Vector2.Zero);
                var substituteAlphaNode = new MaterialShaderClassNode { MixinReference = new AssetReference<EffectShaderAsset>(Guid.Empty, "ComputeColorSubstituteAlphaWithColor") };
                substituteAlphaNode.CompositionNodes.Add("color1", colorNode);
                substituteAlphaNode.CompositionNodes.Add("color2", alphaNode);

                // set the parameters of the children so that they match the original texture
                var children = new[] { colorNode, alphaNode };
                foreach (var childTexture in children)
                {
                    childTexture.Sampler.AddressModeU = textureNode.Sampler.AddressModeU;
                    childTexture.Sampler.AddressModeV = textureNode.Sampler.AddressModeV;
                    childTexture.Sampler.Filtering = textureNode.Sampler.Filtering;
                    childTexture.Offset = textureNode.Offset;
                    childTexture.Sampler.SamplerParameterKey = textureNode.Sampler.SamplerParameterKey;
                    childTexture.Scale = textureNode.Scale;
                    childTexture.TexcoordIndex = textureNode.TexcoordIndex;
                }

                // copy the parameter key on the color and let the one of the alpha null so that it is set automatically to available value later
                colorNode.Key = textureNode.Key;
                alphaNode.Key = null;

                // update all the material references to the new node
                nodeReplacer.Replace(textureNode, substituteAlphaNode);
            }
            
            return modifiedMaterial;
        }
 /// <summary>
 /// Creates and instance of InstancedTriangleMesh
 /// Call the Static Method GetInstacedMesh to get the InstancedMeshShape obj
 /// </summary>
 /// <param name="InstancedMeshShape">The instanced mesh shape.</param>
 /// <param name="pos">The pos.</param>
 /// <param name="rotation">The rotation.</param>
 /// <param name="scale">The scale.</param>
 /// <param name="materialDescription">The material description.</param>
 /// <param name="TriangleSidedness">The triangle sidedness.</param>
 public InstancedTriangleMeshObject(InstancedMeshShape InstancedMeshShape, Vector3 pos, Matrix rotation, Vector3 scale, MaterialDescription materialDescription, TriangleSidedness TriangleSidedness = TriangleSidedness.Counterclockwise)
 {
     instancedMesh = new InstancedMesh(InstancedMeshShape,new BEPUphysics.MathExtensions.AffineTransform(scale,Quaternion.CreateFromRotationMatrix(rotation),pos));
     instancedMesh.Material = new BEPUphysics.Materials.Material(materialDescription.StaticFriction, materialDescription.DynamicFriction, materialDescription.Bounciness);
     instancedMesh.Sidedness = TriangleSidedness;
     this.rotation = rotation;
     this.scale = scale;
 }
 public CapsuleObject(Vector3 pos, float height, float radius, float mass,Matrix? orientation,MaterialDescription md = null)
     : base(md,mass)
 {
     if (!orientation.HasValue)
         orientation = Matrix.Identity;
     
     entity = new Capsule(pos, height, radius, mass);
     entity.Orientation = Quaternion.CreateFromRotationMatrix(orientation.Value);            
 }
        public CylinderObject(Vector3 pos, float altura, float raio, Vector3? scale = null, float mass = 10,Matrix? orientation = null,MaterialDescription md=null)
            : base(md,mass)
        {
            if (!orientation.HasValue)
                orientation = Matrix.Identity;

            if (!scale.HasValue)
                scale = Vector3.One;

            entity = new Cylinder(pos, altura * scale.Value.Y, raio * scale.Value.X, mass);
            this.scale = scale.Value;
            entity.Orientation = Quaternion.CreateFromRotationMatrix(orientation.Value);            
        }
Ejemplo n.º 9
0
        public BoxObject(Vector3 pos, float xlen , float ylen , float zlen, float mass = 10, Vector3? scale = null, Matrix? orientation = null, MaterialDescription materialDescription = null)
            : base(materialDescription, mass)
        {
            if (!orientation.HasValue)
                orientation = Matrix.Identity;

            if (!scale.HasValue)
                scale = Vector3.One;

            this.scale = scale.Value;
            entity = new Box(pos, xlen * this.scale.X, ylen * this.scale.Y, zlen * this.scale.Z, mass);
            entity.Orientation = Quaternion.CreateFromRotationMatrix(orientation.Value);            
        }        
Ejemplo n.º 10
0
        private PhysX()
        {
            try
            {
                Core = new StillDesign.PhysX.Core();
            }
            catch (Exception exception)
            {
                //ScreenManager.Graphics.IsFullScreen = false;
                //ScreenManager.Graphics.ApplyChanges();

                //MessageBox.Show("Error initializing PhysX.\n- Did you install the nVidia PhysX System Software?\n\n" + exception.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }

            //Core.SetParameter(PhysicsParameter.SkinWidth, (float)0.01f);
            Core.SetParameter(PhysicsParameter.VisualizationScale, (float)0f);
            Core.SetParameter(PhysicsParameter.ContinuousCollisionDetection, false);
            Core.SetParameter(PhysicsParameter.VisualizeCollisionShapes, true);
            Core.SetParameter(PhysicsParameter.VisualizeCollisionAxes, false);
            Core.SetParameter(PhysicsParameter.VisualizeBodyAxes, false);
            Core.SetParameter(PhysicsParameter.VisualizeContactNormal, false);
            Core.SetParameter(PhysicsParameter.VisualizeContactForce, false);
            Core.SetParameter(PhysicsParameter.VisualizeActorAxes, false);

            SceneDescription sceneDescription = new SceneDescription();
            sceneDescription.Gravity = new Vector3(0f, Gravity, 0f);
            sceneDescription.TimestepMethod = TimestepMethod.Fixed;

            sceneDescription.Flags = SceneFlag.SimulateSeparateThread;
            sceneDescription.ThreadMask = 0xfffffffe;
            Scene = Core.CreateScene(sceneDescription);

            Scene.UserContactReport = ContactReport.Instance;
            Scene.UserTriggerReport = TriggerReport.Instance;

            MaterialDescription description = new MaterialDescription();
            description.Restitution = 0.1f;
            description.DynamicFriction = 0.2f;
            Scene.DefaultMaterial.LoadFromDescription(description);
            InitScene();
        }
Ejemplo n.º 11
0
        private void SetupSimulation()
        {
            //creating the simulation
            CreateScene();

            //definig a material
            var materialDesc = new MaterialDescription
                                   {
                                       DynamicFriction = Friction,
                                       StaticFriction = Friction,
                                       Restitution = Restitution,
                                       FrictionCombineMode = CombineMode.Average,
                                       RestitutionCombineMode = CombineMode.Average
                                   };
            Nx.Material material = _scene.CreateMaterial(materialDesc);

            CreateGround(material);

            CreateBoxes(material);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MobileMeshObject "/> class.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="pos">The pos.</param>
        /// <param name="rotation">The rotation.</param>
        /// <param name="scale">The scale.</param>
        /// <param name="materialDescription">The material description.</param>
        /// <param name="MobileMeshSolidity">The mobile mesh solidity.</param>
        /// <param name="mass">The mass.</param>
        public MobileMeshObject(IModelo model, Vector3 pos, Matrix? rotation = null, Vector3? scale = null, MaterialDescription materialDescription = null,MobileMeshSolidity MobileMeshSolidity = MobileMeshSolidity.Solid,float mass = 10)
        {
            if (materialDescription == null)
                materialDescription = MaterialDescription.DefaultBepuMaterial();

            if (!rotation.HasValue)
                rotation = Matrix.Identity;

            if (!scale.HasValue)
                scale = Vector3.One;


            System.Diagnostics.Debug.Assert(scale != Vector3.Zero);
            System.Diagnostics.Debug.Assert(model != null);
            
            this.scale = scale.Value;            
            Vector3[] vertices = null;
            int[] indices = null;
            ExtractData(ref vertices, ref indices, model);
            triangleGroup = new MobileMesh(vertices, indices, new AffineTransform(scale.Value, Quaternion.CreateFromRotationMatrix(rotation.Value), pos), MobileMeshSolidity,mass);        
            triangleGroup.Material = new BEPUphysics.Materials.Material(materialDescription.StaticFriction, materialDescription.DynamicFriction, materialDescription.Bounciness);
        }
Ejemplo n.º 13
0
        private Actor CreateActor(RigidBodyDescriptor descriptor, Scene scene)
        {
         
            var materialDesc = new MaterialDescription
            {
                DynamicFriction = 0.5f,
                StaticFriction = 0.5f,
                Restitution = 0.7f,
                FrictionCombineMode = CombineMode.Average,
                RestitutionCombineMode = CombineMode.Average
            };
            DefaultMaterial = scene.CreateMaterial(materialDesc);
            var boxDesc = new BoxShapeDescription
            {
                Material = DefaultMaterial,
                Dimensions = new Vector3(1, 1, 1)
            };
            ///////////////////////////////////////////////



            //resolve the motion type
            var rigidBodyDesc = descriptor.MotionType == MotionType.Static
                                    ? null
                                    : new BodyDescription();
            if (descriptor.MotionType == MotionType.Kinematic)
                rigidBodyDesc.BodyFlags = BodyFlag.Kinematic;

            HasDefaultShape = true;
            var actorDesc = new ActorDescription(boxDesc)
                                {
                                    BodyDescription = rigidBodyDesc,
                                    Density = 10.0f,
                                    GlobalPose = descriptor.Pose.ToPhysX(),
                                    UserData = descriptor.UserData
                                };
            return scene.CreateActor(actorDesc);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BepuEntityObject"/> class.
 /// </summary>
 /// <param name="md">The md.</param>
 /// <param name="mass">The mass.</param>
 public BepuEntityObject(MaterialDescription md, float mass)
 {
     if (md == null)
         md = MaterialDescription.DefaultBepuMaterial();
     this.materialDecription = md;
     this.mass = mass;            
 }
Ejemplo n.º 15
0
        public ObjectMock(GraphicFactory GraphicFactory, String modelName, Vector3 position, Matrix orientation, Vector3 scale)
        {
            this.modelName   = modelName;
            this.position    = position;
            this.scale       = scale;
            this.orientation = orientation;
            Modelo           = new SimpleModel(GraphicFactory, modelName);
            PhysicObject     = new TriangleMeshObject(Modelo, position, orientation, scale, MaterialDescription.DefaultBepuMaterial());
            ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());

            Material          = new ForwardMaterial(shader);
            IObjectAttachment = new List <IObjectAttachment>();
        }
Ejemplo n.º 16
0
        public CylinderObject(Vector3 pos, float altura, float raio, Vector3?scale = null, float mass = 10, Matrix?orientation = null, MaterialDescription md = null)
            : base(md, mass)
        {
            if (!orientation.HasValue)
            {
                orientation = Matrix.Identity;
            }

            if (!scale.HasValue)
            {
                scale = Vector3.One;
            }

            entity             = new Cylinder(pos, altura * scale.Value.Y, raio * scale.Value.X, mass);
            this.scale         = scale.Value;
            entity.Orientation = Quaternion.CreateFromRotationMatrix(orientation.Value);
        }
        void CreateFrom3DsPhysicalMaterial(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            float   floatProperty;
            Vector4 vectorProperty;
            TexturePropertyDescription textureProperty;
            Shader shader;

            description.TryGetProperty("transparency", out floatProperty);
            bool hasTransparencyMap =
                description.TryGetProperty("transparency_map", out textureProperty);

            if (floatProperty > 0.0f || hasTransparencyMap)
            {
                shader = AssetDatabase.LoadAssetAtPath <Shader>(k_ShaderTransparentPath);
                if (shader == null)
                {
                    return;
                }

                material.shader = shader;
                if (hasTransparencyMap)
                {
                    material.SetTexture("_TRANSPARENCY_MAP", textureProperty.texture);
                    material.SetFloat("_TRANSPARENCY", 1.0f);
                }
                else
                {
                    material.SetFloat("_TRANSPARENCY", floatProperty);
                }
            }
            else
            {
                shader = AssetDatabase.LoadAssetAtPath <Shader>(k_ShaderPath);
                if (shader == null)
                {
                    return;
                }

                material.shader = shader;
            }

            foreach (var clip in clips)
            {
                clip.ClearCurves();
            }

            RemapPropertyFloat(description, material, "base_weight", "_BASE_COLOR_WEIGHT");
            if (description.TryGetProperty("base_color_map", out textureProperty))
            {
                SetMaterialTextureProperty("_BASE_COLOR_MAP", material, textureProperty);
            }
            else if (description.TryGetProperty("base_color", out vectorProperty))
            {
                if (QualitySettings.activeColorSpace == ColorSpace.Gamma)
                {
                    vectorProperty.x = Mathf.LinearToGammaSpace(vectorProperty.x);
                    vectorProperty.y = Mathf.LinearToGammaSpace(vectorProperty.y);
                    vectorProperty.z = Mathf.LinearToGammaSpace(vectorProperty.z);
                    vectorProperty.w = Mathf.LinearToGammaSpace(vectorProperty.w);
                }
                material.SetColor("_BASE_COLOR", vectorProperty);
            }

            RemapPropertyFloat(description, material, "reflectivity", "_REFLECTIONS_WEIGHT");
            RemapPropertyTextureOrColor(description, material, "refl_color", "_REFLECTIONS_COLOR");
            RemapPropertyTextureOrFloat(description, material, "metalness", "_METALNESS");
            RemapPropertyTextureOrFloat(description, material, "roughness", "_REFLECTIONS_ROUGHNESS");
            RemapPropertyTextureOrFloat(description, material, "trans_ior", "_REFLECTIONS_IOR");
            RemapPropertyFloat(description, material, "emission", "_EMISSION_WEIGHT");
            RemapPropertyTextureOrColor(description, material, "emit_color", "_EMISSION_COLOR");

            RemapPropertyFloat(description, material, "bump_map_amt", "_BUMP_MAP_STRENGTH");
            RemapPropertyTexture(description, material, "bump_map", "_BUMP_MAP");
        }
Ejemplo n.º 18
0
        public TerrainObject(GraphicFactory gfactory, Vector3 translation, Matrix rotation, float[,] heights, MaterialDescription materialDesc, BEPUphysics.CollisionShapes.QuadTriangleOrganization triangleorientation = BEPUphysics.CollisionShapes.QuadTriangleOrganization.BottomLeftUpperRight)
        {
            terrainWidth  = heights.GetLength(0);
            terrainHeight = heights.GetLength(1);

            //Create the terrain.
            BEPUphysics.CollisionShapes.TerrainShape shape = new BEPUphysics.CollisionShapes.TerrainShape(heights, triangleorientation);

            terrain = new Terrain(shape, new BEPUphysics.MathExtensions.AffineTransform(Vector3.One, Quaternion.CreateFromRotationMatrix(rotation), translation));
            terrain.ImproveBoundaryBehavior = true;

            SetMaterialDescription(materialDesc);
        }
Ejemplo n.º 19
0
        public VehicleChassis(Vehicle vehicle)
        {
            Vehicle = vehicle;

            Wheels = new List<VehicleWheel>();

            VehicleFile carFile = vehicle.Config;

            ActorDescription actorDesc = new ActorDescription();

            actorDesc.BodyDescription = new BodyDescription();
            actorDesc.BodyDescription.Mass = carFile.Mass;
            var boxDesc = new BoxShapeDescription();
            boxDesc.Size = carFile.BoundingBox.GetSize();
            boxDesc.LocalPosition = carFile.BoundingBox.GetCenter();
            boxDesc.Name = PhysXConsts.VehicleBody;
            boxDesc.Flags |= ShapeFlag.PointContactForce;
            actorDesc.Shapes.Add(boxDesc);

            foreach (Vector3 extraPoint in carFile.ExtraBoundingBoxPoints)
            {
                var extraDesc = new SphereShapeDescription(0.2f);
                extraDesc.LocalPosition = extraPoint;
                extraDesc.Mass = 0;
                actorDesc.Shapes.Add(extraDesc);
            }

            using (UtilitiesLibrary lib = new UtilitiesLibrary())
            {
                Vector3 size = carFile.Size;
                Vector3 inertiaTensor = lib.ComputeBoxInteriaTensor(Vector3.Zero, carFile.Mass, size);
                //actorDesc.BodyDescription.MassSpaceInertia = inertiaTensor;
            }

            TireFunctionDescription lngTFD = new TireFunctionDescription();
            lngTFD.ExtremumSlip = 0.1f;
            lngTFD.ExtremumValue = 4f;
            lngTFD.AsymptoteSlip = 2.0f;
            lngTFD.AsymptoteValue = 3.2f;

            _rearLateralTireFn = new TireFunctionDescription();

            _rearLateralTireFn.ExtremumSlip = 0.2f;
            _rearLateralTireFn.ExtremumValue = 2.1f;
            _rearLateralTireFn.AsymptoteSlip = 0.0013f * carFile.Mass;
            _rearLateralTireFn.AsymptoteValue = 0.02f;

            _frontLateralTireFn = _rearLateralTireFn;
            _frontLateralTireFn.ExtremumValue = 1.9f;

            MaterialDescription md = new MaterialDescription();
            md.Flags = MaterialFlag.DisableFriction;
            Material m = PhysX.Instance.Scene.CreateMaterial(md);

            int wheelIndex = 0;

            foreach (CWheelActor wheel in carFile.WheelActors)
            {
                WheelShapeDescription wheelDesc = new WheelShapeDescription();
                wheelDesc.InverseWheelMass = 0.08f;
                wheelDesc.LongitudalTireForceFunction = lngTFD;
                wheelDesc.Flags = WheelShapeFlag.ClampedFriction;
                wheelDesc.Material = m;

                wheelDesc.Radius = wheel.IsDriven ? carFile.DrivenWheelRadius : carFile.NonDrivenWheelRadius;
                wheelDesc.SuspensionTravel = (wheel.IsFront ? carFile.SuspensionGiveFront : carFile.SuspensionGiveRear) * 18;

                float heightModifier = (wheelDesc.SuspensionTravel + wheelDesc.Radius) / wheelDesc.SuspensionTravel;

                SpringDescription spring = new SpringDescription();
                if (carFile.Mass > 3000)
                    spring.SpringCoefficient = 10.5f * heightModifier * carFile.Mass;
                else
                    spring.SpringCoefficient = 6.5f * heightModifier * Math.Min(1000, carFile.Mass);
                spring.DamperCoefficient = carFile.SuspensionDamping * 6f;

                wheelDesc.Suspension = spring;
                wheelDesc.LocalPosition = wheel.Position;
                wheelDesc.Name = (wheelIndex).ToString();
                wheelIndex++;

                wheelDesc.LateralTireForceFunction = wheel.IsFront ? _frontLateralTireFn : _rearLateralTireFn;
                actorDesc.Shapes.Add(wheelDesc);
            }

            _physXActor = PhysX.Instance.Scene.CreateActor(actorDesc);

            _heightOffset = _physXActor.Shapes[0].LocalPosition.Y * -2;
            if (_heightOffset < 0) _heightOffset = 0;

            foreach (Shape shape in _physXActor.Shapes)
            {
                shape.LocalPosition += new Vector3(0, _heightOffset, 0);
                if (shape is WheelShape)
                {
                    wheelIndex = int.Parse(shape.Name);
                    Wheels.Add(new VehicleWheel(this, carFile.WheelActors[wheelIndex], (WheelShape)shape, carFile.WheelActors[wheelIndex].IsLeft ? 0.17f : -0.17f) { Index = wheelIndex });
                }
            }

            _physXActor.Group = PhysXConsts.VehicleId;
            _physXActor.UserData = vehicle;

            _physXActor.WakeUp(60.0f);

            //_physXActor.RaiseBodyFlag(BodyFlag.DisableGravity);

            //set center of mass
            Vector3 massPos = carFile.CenterOfMass;
            massPos.Y = carFile.WheelActors[0].Position.Y - carFile.NonDrivenWheelRadius + _heightOffset + 0.35f;
            _massPos = massPos;
            _physXActor.SetCenterOfMassOffsetLocalPosition(massPos);

            //a real power curve doesnt work too well :)
            List<float> power = new List<float>(new float[] { 0.5f, 0.5f, 0.5f, 1f, 1f, 1.0f, 1.0f, 0 });
            List<float> ratios = new List<float>(new float[] { 3.227f, 2.360f, 1.685f, 1.312f, 1.000f, 0.793f });

            BaseGearbox gearbox = BaseGearbox.Create(false, ratios, 0.4f);
            Motor = new Motor(power, carFile.EnginePower, 6f, carFile.TopSpeed, gearbox);
            Motor.Gearbox.CurrentGear = 0;
        }
        void CreateFromAutodeskInteractiveMaterial(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var shader = Shader.Find("Autodesk Interactive");

            if (shader == null)
            {
                context.LogImportError("ThreeDSMaterialDescriptionPreprocessor cannot find a shader named 'Autodesk Interactive'.");
                return;
            }
            material.shader = shader;

            float   floatProperty;
            Vector4 vectorProperty;
            TexturePropertyDescription textureProperty;
            AnimationCurve             curve;

            Vector2 uvOffset = new Vector2(0.0f, 0.0f);
            Vector2 uvScale  = new Vector2(1.0f, 1.0f);

            if (description.TryGetProperty("uv_offset", out vectorProperty))
            {
                uvOffset.x = vectorProperty.x;
                uvOffset.y = -vectorProperty.y;
            }
            if (description.TryGetProperty("uv_scale", out vectorProperty))
            {
                uvScale.x = vectorProperty.x;
                uvScale.y = vectorProperty.y;
            }

            for (int i = 0; i < clips.Length; i++)
            {
                if (description.HasAnimationCurveInClip(clips[i].name, "uv_scale.x") ||
                    description.HasAnimationCurveInClip(clips[i].name, "uv_scale.y") ||
                    description.HasAnimationCurveInClip(clips[i].name, "uv_offset.x") ||
                    description.HasAnimationCurveInClip(clips[i].name, "uv_offset.y")
                    )
                {
                    if (description.TryGetAnimationCurve(clips[i].name, "uv_scale.x", out curve))
                    {
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.x", curve);
                    }
                    else
                    {
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.x", AnimationCurve.Constant(0.0f, 1.0f, 1.0f));
                    }

                    if (description.TryGetAnimationCurve(clips[i].name, "uv_scale.y", out curve))
                    {
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.y", curve);
                    }
                    else
                    {
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.y", AnimationCurve.Constant(0.0f, 1.0f, 1.0f));
                    }

                    if (description.TryGetAnimationCurve(clips[i].name, "uv_offset.x", out curve))
                    {
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.z", curve);
                    }
                    else
                    {
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.z", AnimationCurve.Constant(0.0f, 1.0f, 0.0f));
                    }

                    if (description.TryGetAnimationCurve(clips[i].name, "uv_offset.y", out curve))
                    {
                        ConvertKeys(curve, ConvertFloatNegate);
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.w", curve);
                    }
                    else
                    {
                        clips[i].SetCurve("", typeof(Material), "_MainTex_ST.w", AnimationCurve.Constant(0.0f, 1.0f, 0.0f));
                    }
                }
            }

            float opacity        = 1.0f;
            float alphaThreshold = 0.0f;

            description.TryGetProperty("opacity", out opacity);
            description.TryGetProperty("mask_threshold", out alphaThreshold);
            if (alphaThreshold > 0.0f || description.HasAnimationCurve("mask_threshold"))
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Cutout);
                material.SetOverrideTag("RenderType", "TransparentCutout");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 1);
                material.EnableKeyword("_ALPHATEST_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else if (opacity < 1.0f ||
                     description.HasAnimationCurve("opacity") ||
                     (description.TryGetProperty("use_opacity_map", out floatProperty) && floatProperty == 1.0f))
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Transparent);
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Opaque);
                material.SetOverrideTag("RenderType", "");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
            }

            if (description.TryGetProperty("use_color_map", out floatProperty) && floatProperty == 1.0f ||
                description.TryGetProperty("use_opacity_map", out floatProperty) && floatProperty == 1.0f)
            {
                if (description.TryGetProperty("TEX_color_map", out textureProperty))
                {
                    material.SetTexture("_MainTex", textureProperty.texture);
                    material.SetTextureOffset("_MainTex", uvOffset);
                    material.SetTextureScale("_MainTex", uvScale);
                    material.SetColor("_Color", new Vector4(1.0f, 1.0f, 1.0f, opacity));

                    if (alphaThreshold > 0.0f || description.HasAnimationCurve("mask_threshold"))
                    {
                        material.SetFloat("_Cutoff", alphaThreshold);
                        RemapCurve(description, clips, "mask_threshold", "_Cutoff");
                    }
                }
            }
            else
            {
                description.TryGetProperty("base_color", out vectorProperty);
                vectorProperty.w = opacity;
                material.SetColor("_Color", vectorProperty);
                RemapColorCurves(description, clips, "base_color", "_Color");
            }

            if (description.HasAnimationCurve("opacity"))
            {
                for (int i = 0; i < clips.Length; i++)
                {
                    AnimationCurve opacityCurve;
                    description.TryGetAnimationCurve(clips[i].name, "opacity", out opacityCurve);
                    clips[i].SetCurve("", typeof(Material), "_Color.a", opacityCurve);

                    if (!description.HasAnimationCurveInClip(clips[i].name, "base_color.x"))
                    {
                        Vector4 diffuseColor;
                        description.TryGetProperty("base_color", out diffuseColor);
                        clips[i].SetCurve("", typeof(Material), "_Color.r", AnimationCurve.Constant(0.0f, 1.0f, diffuseColor.x));
                        clips[i].SetCurve("", typeof(Material), "_Color.g", AnimationCurve.Constant(0.0f, 1.0f, diffuseColor.y));
                        clips[i].SetCurve("", typeof(Material), "_Color.b", AnimationCurve.Constant(0.0f, 1.0f, diffuseColor.z));
                    }
                }
            }

            if (description.TryGetProperty("use_normal_map", out floatProperty) && floatProperty == 1.0f)
            {
                if (description.TryGetProperty("TEX_normal_map", out textureProperty))
                {
                    material.SetTexture("_BumpMap", textureProperty.texture);
                    material.SetTextureOffset("_BumpMap", uvOffset);
                    material.SetTextureScale("_BumpMap", uvScale);
                    material.EnableKeyword("_NORMALMAP");
                }
            }

            if (description.TryGetProperty("use_metallic_map", out floatProperty) && floatProperty == 1.0f)
            {
                if (description.TryGetProperty("TEX_metallic_map", out textureProperty))
                {
                    material.SetTexture("_MetallicGlossMap", textureProperty.texture);
                    material.SetTextureOffset("_MetallicGlossMap", uvOffset);
                    material.SetTextureScale("_MetallicGlossMap", uvScale);
                    material.EnableKeyword("_METALLICGLOSSMAP");
                }
            }
            else
            {
                if (description.TryGetProperty("metallic", out floatProperty))
                {
                    material.SetFloat("_Metallic", floatProperty);
                    RemapCurve(description, clips, "metallic", "_Metallic");
                }
            }

            if (description.TryGetProperty("use_roughness_map", out floatProperty) && floatProperty == 1.0f)
            {
                if (description.TryGetProperty("TEX_roughness_map", out textureProperty))
                {
                    material.SetTexture("_SpecGlossMap", textureProperty.texture);
                    material.SetTextureOffset("_SpecGlossMap", uvOffset);
                    material.SetTextureScale("_SpecGlossMap", uvScale);
                    material.EnableKeyword("_SPECGLOSSMAP");
                }
            }
            else
            {
                if (description.TryGetProperty("roughness", out floatProperty))
                {
                    material.SetFloat("_Glossiness", floatProperty);
                    RemapCurve(description, clips, "roughness", "_Glossiness");
                }
            }

            if (description.TryGetProperty("use_emissive_map", out floatProperty) && floatProperty == 1.0f)
            {
                if (description.TryGetProperty("TEX_emissive_map", out textureProperty))
                {
                    Vector4 emissiveColor = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
                    if (description.TryGetProperty("emissive_intensity", out floatProperty))
                    {
                        emissiveColor *= floatProperty;
                    }
                    material.SetColor("_EmissionColor", emissiveColor);
                    material.SetTexture("_EmissionMap", textureProperty.texture);
                    material.SetTextureOffset("_EmissionMap", uvOffset);
                    material.SetTextureScale("_EmissionMap", uvScale);
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }

                if (description.HasAnimationCurve("emissive_intensity"))
                {
                    Vector4 emissiveColor;
                    description.TryGetProperty("emissive", out emissiveColor);

                    for (int i = 0; i < clips.Length; i++)
                    {
                        description.TryGetAnimationCurve(clips[i].name, "emissive_intensity", out curve);
                        // remap emissive intensity to emission color
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.r", curve);
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.g", curve);
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.b", curve);
                    }
                }
            }
            else if (description.TryGetProperty("emissive", out vectorProperty))
            {
                if (vectorProperty.x > 0.0f || vectorProperty.y > 0.0f || vectorProperty.z > 0.0f)
                {
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                    material.EnableKeyword("_EMISSION");
                }

                if (description.TryGetProperty("emissive_intensity", out floatProperty))
                {
                    vectorProperty *= floatProperty;
                }

                material.SetColor("_EmissionColor", vectorProperty);


                if (description.HasAnimationCurve("emissive.x"))
                {
                    if (description.HasAnimationCurve("emissive_intensity"))
                    {
                        // combine color and intensity.
                        for (int i = 0; i < clips.Length; i++)
                        {
                            AnimationCurve intensityCurve;
                            description.TryGetAnimationCurve(clips[i].name, "emissive_intensity", out intensityCurve);

                            description.TryGetAnimationCurve(clips[i].name, "emissive.x", out curve);
                            MultiplyCurves(curve, intensityCurve);
                            clips[i].SetCurve("", typeof(Material), "_EmissionColor.r", curve);

                            description.TryGetAnimationCurve(clips[i].name, "emissive.y", out curve);
                            MultiplyCurves(curve, intensityCurve);
                            clips[i].SetCurve("", typeof(Material), "_EmissionColor.g", curve);

                            description.TryGetAnimationCurve(clips[i].name, "emissive.z", out curve);
                            MultiplyCurves(curve, intensityCurve);
                            clips[i].SetCurve("", typeof(Material), "_EmissionColor.b", curve);
                        }
                    }
                    else
                    {
                        RemapColorCurves(description, clips, "emissive", "_EmissionColor");
                    }
                }
                else if (description.HasAnimationCurve("emissive_intensity"))
                {
                    Vector4 emissiveColor;
                    description.TryGetProperty("emissive", out emissiveColor);

                    for (int i = 0; i < clips.Length; i++)
                    {
                        description.TryGetAnimationCurve(clips[i].name, "emissive_intensity", out curve);
                        // remap emissive intensity to emission color
                        AnimationCurve curveR = new AnimationCurve();
                        ConvertAndCopyKeys(curveR, curve, value => ConvertFloatMultiply(emissiveColor.x, value));
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.r", curveR);

                        AnimationCurve curveG = new AnimationCurve();
                        ConvertAndCopyKeys(curveG, curve, value => ConvertFloatMultiply(emissiveColor.y, value));
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.g", curveG);

                        AnimationCurve curveB = new AnimationCurve();
                        ConvertAndCopyKeys(curveB, curve, value => ConvertFloatMultiply(emissiveColor.z, value));
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.b", curveB);
                    }
                }
            }

            if (description.TryGetProperty("use_ao_map", out floatProperty) && floatProperty == 1.0f)
            {
                if (description.TryGetProperty("TEX_ao_map", out textureProperty))
                {
                    material.SetTexture("_OcclusionMap", textureProperty.texture);
                    material.SetTextureOffset("_OcclusionMap", uvOffset);
                    material.SetTextureScale("_OcclusionMap", uvScale);
                }
            }
        }
Ejemplo n.º 21
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            {
                SimpleModel           simpleModel = new SimpleModel(factory, "Model//cenario");
                TriangleMeshObject    tmesh       = new TriangleMeshObject(simpleModel, Vector3.Zero, Matrix.Identity, Vector3.One, MaterialDescription.DefaultBepuMaterial());
                ForwardXNABasicShader shader      = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial       fmaterial   = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, tmesh);
                this.World.AddObject(obj);
            }

            NeoforceGui guiManager = this.Gui as NeoforceGui;

            System.Diagnostics.Debug.Assert(guiManager != null);

            // Create and setup Window control.
            Window window = new Window(guiManager.Manager);

            window.Init();
            window.Text   = "Getting Started";
            window.Width  = 480;
            window.Height = 200;
            window.Center();
            window.Visible = true;

            // Create Button control and set the previous window as its parent.
            Button button = new Button(guiManager.Manager);

            button.Init();
            button.Text   = "OK";
            button.Width  = 72;
            button.Height = 24;
            button.Left   = (window.ClientWidth / 2) - (button.Width / 2);
            button.Top    = window.ClientHeight - button.Height - 8;
            button.Anchor = Anchors.Bottom;
            button.Parent = window;

            // Add the window control to the manager processing queue.
            guiManager.Manager.Add(window);



            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion

            this.World.CameraManager.AddCamera(new CameraFirstPerson(true, GraphicInfo));

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//cubemap");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
        void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var shader = Shader.Find("Autodesk Interactive");

            if (shader == null)
            {
                context.LogImportError("ThreeDSMaterialDescriptionPreprocessor cannot find a shader named 'Autodesk Interactive'.");
                return;
            }
            material.shader = shader;

            float   floatProperty;
            Vector4 vectorProperty;
            TexturePropertyDescription textureProperty;

            if (description.TryGetProperty("transmission", out floatProperty) && floatProperty > 0.0f)
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Transparent);
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Opaque);
                material.SetOverrideTag("RenderType", "");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
            }
            if (description.TryGetProperty("baseColor", out textureProperty))
            {
                SetMaterialTextureProperty("_MainTex", material, textureProperty);
                Color baseColor = new Color(1.0f, 1.0f, 1.0f, 1.0f - floatProperty);
                material.SetColor("_Color", baseColor);
            }
            else if (description.TryGetProperty("baseColor", out vectorProperty))
            {
                if (QualitySettings.activeColorSpace == ColorSpace.Gamma)
                {
                    vectorProperty.x = Mathf.LinearToGammaSpace(vectorProperty.x);
                    vectorProperty.y = Mathf.LinearToGammaSpace(vectorProperty.y);
                    vectorProperty.z = Mathf.LinearToGammaSpace(vectorProperty.z);
                }

                vectorProperty.w = 1.0f - floatProperty;
                material.SetColor("_Color", vectorProperty);

                RemapColorCurves(description, clips, "baseColor", "_Color");
            }

            if (description.HasAnimationCurve("transmission"))
            {
                for (int i = 0; i < clips.Length; i++)
                {
                    AnimationCurve opacityCurve;
                    description.TryGetAnimationCurve(clips[i].name, "transmission", out opacityCurve);
                    clips[i].SetCurve("", typeof(Material), "_Color.a", opacityCurve);

                    if (!description.HasAnimationCurveInClip(clips[i].name, "baseColor.x"))
                    {
                        Vector4 diffuseColor;
                        description.TryGetProperty("baseColor", out diffuseColor);
                        clips[i].SetCurve("", typeof(Material), "_Color.r", AnimationCurve.Constant(0.0f, 1.0f, diffuseColor.x));
                        clips[i].SetCurve("", typeof(Material), "_Color.g", AnimationCurve.Constant(0.0f, 1.0f, diffuseColor.y));
                        clips[i].SetCurve("", typeof(Material), "_Color.b", AnimationCurve.Constant(0.0f, 1.0f, diffuseColor.z));
                    }
                }
            }

            if (description.TryGetProperty("normalCamera", out textureProperty))
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                material.EnableKeyword("_NORMALMAP");
            }
            if (description.TryGetProperty("specularRoughness", out textureProperty))
            {
                SetMaterialTextureProperty("_SpecGlossMap", material, textureProperty);
                material.EnableKeyword("_SPECGLOSSMAP");
            }
            else if (description.TryGetProperty("specularRoughness", out floatProperty))
            {
                material.SetFloat("_Glossiness", floatProperty);
                RemapCurve(description, clips, "specularRoughness", "_Glossiness");
            }
            if (description.TryGetProperty("metalness", out textureProperty))
            {
                SetMaterialTextureProperty("_MetallicGlossMap", material, textureProperty);
                material.EnableKeyword("_METALLICGLOSSMAP");
                RemapCurve(description, clips, "metalness", "_MetallicGlossMap");
            }

            if (description.TryGetProperty("emission", out floatProperty) && floatProperty > 0.0f)
            {
                material.EnableKeyword("_EMISSION");
                material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;

                Color emissiveColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
                if (description.TryGetProperty("emissionColor", out textureProperty))
                {
                    emissiveColor *= floatProperty;
                    SetMaterialTextureProperty("_EmissionMap", material, textureProperty);
                    material.SetColor("_EmissionColor", emissiveColor);
                }
                else if (description.TryGetProperty("emissionColor", out vectorProperty))
                {
                    emissiveColor = vectorProperty * floatProperty;
                    material.SetColor("_EmissionColor", emissiveColor);
                }
            }

            if (description.HasAnimationCurve("emissionColor.x"))
            {
                if (description.HasAnimationCurve("emission"))
                {
                    // combine color and intensity.
                    AnimationCurve curve;
                    for (int i = 0; i < clips.Length; i++)
                    {
                        AnimationCurve intensityCurve;
                        description.TryGetAnimationCurve(clips[i].name, "emission", out intensityCurve);

                        description.TryGetAnimationCurve(clips[i].name, "emissionColor.x", out curve);
                        MultiplyCurves(curve, intensityCurve);
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.r", curve);

                        description.TryGetAnimationCurve(clips[i].name, "emissionColor.y", out curve);
                        MultiplyCurves(curve, intensityCurve);
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.g", curve);

                        description.TryGetAnimationCurve(clips[i].name, "emissionColor.z", out curve);
                        MultiplyCurves(curve, intensityCurve);
                        clips[i].SetCurve("", typeof(Material), "_EmissionColor.b", curve);
                    }
                }
                else
                {
                    RemapColorCurves(description, clips, "emission", "_EmissionColor");
                }
            }
            else if (description.HasAnimationCurve("emission"))
            {
                Vector4 emissiveColor;
                description.TryGetProperty("emissionColor", out emissiveColor);
                AnimationCurve curve;
                for (int i = 0; i < clips.Length; i++)
                {
                    description.TryGetAnimationCurve(clips[i].name, "emission", out curve);
                    // remap emissive intensity to emission color
                    AnimationCurve curveR = new AnimationCurve();
                    ConvertAndCopyKeys(curveR, curve, value => ConvertFloatMultiply(emissiveColor.x, value));
                    clips[i].SetCurve("", typeof(Material), "_EmissionColor.r", curveR);

                    AnimationCurve curveG = new AnimationCurve();
                    ConvertAndCopyKeys(curveG, curve, value => ConvertFloatMultiply(emissiveColor.y, value));
                    clips[i].SetCurve("", typeof(Material), "_EmissionColor.g", curveG);

                    AnimationCurve curveB = new AnimationCurve();
                    ConvertAndCopyKeys(curveB, curve, value => ConvertFloatMultiply(emissiveColor.z, value));
                    clips[i].SetCurve("", typeof(Material), "_EmissionColor.b", curveB);
                }
            }
        }
        void CreateFrom3DsMaxPhysicalMaterial(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var shader = Shader.Find("Autodesk Interactive");

            if (shader == null)
            {
                context.LogImportError("ThreeDSMaterialDescriptionPreprocessor cannot find a shader named 'Autodesk Interactive'.");
                return;
            }
            material.shader = shader;

            float   floatProperty;
            Vector4 vectorProperty;
            TexturePropertyDescription textureProperty;
            float transparency = 0.0f;

            description.TryGetProperty("transparency", out transparency);

            if (transparency > 0.0f)
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Transparent);
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Opaque);
                material.SetOverrideTag("RenderType", "");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
            }

            if (description.TryGetProperty("base_color_map", out textureProperty))
            {
                SetMaterialTextureProperty("_MainTex", material, textureProperty);
                material.SetColor("_Color", new Color(1.0f, 1.0f, 1.0f, 1.0f - transparency));
            }
            else if (description.TryGetProperty("base_color", out vectorProperty))
            {
                vectorProperty.w = 1.0f - transparency;
                material.SetColor("_Color", vectorProperty);
            }
            if (description.TryGetProperty("bump_map", out textureProperty))
            {
                if (description.TryGetProperty("bump_map_amt", out floatProperty))
                {
                    material.SetFloat("_BumpScale", floatProperty);
                }
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                material.EnableKeyword("_NORMALMAP");
            }
            if (description.TryGetProperty("roughness_map", out textureProperty))
            {
                SetMaterialTextureProperty("_SpecGlossMap", material, textureProperty);
                material.EnableKeyword("_SPECGLOSSMAP");
            }
            if (description.TryGetProperty("metalness_map", out textureProperty))
            {
                SetMaterialTextureProperty("_MetallicGlossMap", material, textureProperty);
                material.EnableKeyword("_METALLICGLOSSMAP");
            }

            if (description.TryGetProperty("emit_color", out vectorProperty))
            {
                if (description.TryGetProperty("emission", out floatProperty))
                {
                    vectorProperty *= floatProperty;
                }
                material.SetColor("_EmissionColor", vectorProperty);
                material.EnableKeyword("_EMISSION");
                material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
            }
        }
        /// <summary>
        /// Load content for the screen.
        /// </summary>
        /// <param name="GraphicInfo"></param>
        /// <param name="factory"></param>
        /// <param name="contentManager"></param>
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            RegisterDebugDrawCommand rc = new RegisterDebugDrawCommand(ddrawer);

            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(rc);
            dlines = new DebugLines();
            ddrawer.AddShape(dlines);

            Picking pick = new Picking(this, 2000);

            pick.OnPickedLeftButton += new OnPicked(pick_OnPickedLeftButton);

            wh = new WaypointHandler();

            SimpleModel simpleModel = new SimpleModel(factory, "Model//block");

            simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.White), TextureType.DIFFUSE);
            ///Physic info (position, rotation and scale are set here)
            BoxObject tmesh = new BoxObject(Vector3.Zero, 1, 1, 1, 10, new Vector3(1000, 1, 1000), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());

            tmesh.isMotionLess = true;
            ///Forward Shader (look at this shader construction for more info)
            ForwardXNABasicShader shader = new ForwardXNABasicShader();
            ///Deferred material
            ForwardMaterial fmaterial = new ForwardMaterial(shader);
            ///The object itself
            IObject obj = new IObject(fmaterial, simpleModel, tmesh);

            ///Add to the world
            this.World.AddObject(obj);

            {
                InputPlayableKeyBoard ipk = new SimpleConcreteKeyboardInputPlayable(StateKey.PRESS, Microsoft.Xna.Framework.Input.Keys.Space);
                ipk.KeyStateChange += new KeyStateChange(ipk_KeyStateChange);
                this.BindInput(ipk);
            }

            {
                InputPlayableKeyBoard ipk = new SimpleConcreteKeyboardInputPlayable(StateKey.PRESS, Microsoft.Xna.Framework.Input.Keys.Enter);
                ipk.KeyStateChange += new KeyStateChange(ipk_KeyStateChange2);
                this.BindInput(ipk);
            }

            ///add a camera
            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
        void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            float   floatProperty;
            Vector4 vectorProperty;
            TexturePropertyDescription textureProperty;


            var shader = AssetDatabase.LoadAssetAtPath <Shader>(k_ShaderPath);

            if (shader == null)
            {
                return;
            }


            material.shader = shader;
            foreach (var clip in clips)
            {
                clip.ClearCurves();
            }

            float   opacity = 1.0f;
            Vector4 opacityColor;
            TexturePropertyDescription opacityMap;

            description.TryGetProperty("opacity", out opacityColor);
            bool hasOpacityMap = description.TryGetProperty("opacity", out opacityMap);

            opacity = Mathf.Min(Mathf.Min(opacityColor.x, opacityColor.y), opacityColor.z);

            float transmission;

            description.TryGetProperty("transmission", out transmission);
            if (opacity == 1.0f && !hasOpacityMap)
            {
                opacity = 1.0f - transmission;
            }

            if (opacity < 1.0f || hasOpacityMap)
            {
                if (hasOpacityMap)
                {
                    material.SetTexture("_OPACITY_MAP", opacityMap.texture);
                    material.SetFloat("_OPACITY", 1.0f);
                }
                else
                {
                    material.SetFloat("_OPACITY", opacity);
                }

                material.SetInt("_SrcBlend", 1);
                material.SetInt("_DstBlend", 10);
                material.SetFloat("_BlendMode", (float)BlendMode.Alpha);
                material.SetFloat("_EnableBlendModePreserveSpecularLighting", 1.0f);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
                material.EnableKeyword("_ENABLE_FOG_ON_TRANSPARENT");
                material.renderQueue = 3000;
            }
            else
            {
                material.EnableKeyword("_DOUBLESIDED_ON");
                material.SetInt("_CullMode", 0);
                material.SetInt("_CullModeForward", 0);
                material.doubleSidedGI = true;
            }

            description.TryGetProperty("base", out floatProperty);

            if (description.TryGetProperty("baseColor", out textureProperty))
            {
                SetMaterialTextureProperty("_BASE_COLOR_MAP", material, textureProperty);
                material.SetColor("_BASE_COLOR", Color.white * floatProperty);
            }
            else if (description.TryGetProperty("baseColor", out vectorProperty))
            {
                if (QualitySettings.activeColorSpace == ColorSpace.Gamma)
                {
                    vectorProperty.x = Mathf.LinearToGammaSpace(vectorProperty.x);
                    vectorProperty.y = Mathf.LinearToGammaSpace(vectorProperty.y);
                    vectorProperty.z = Mathf.LinearToGammaSpace(vectorProperty.z);
                }
                material.SetColor("_BASE_COLOR", vectorProperty * floatProperty);
            }

            if (description.TryGetProperty("emission", out floatProperty) && floatProperty > 0.0f)
            {
                remapPropertyColorOrTexture(description, material, "emissionColor", "_EMISSION_COLOR", floatProperty);
            }

            remapPropertyFloatOrTexture(description, material, "metalness", "_METALNESS");

            remapPropertyFloat(description, material, "specular", "_SPECULAR_WEIGHT");

            remapPropertyColorOrTexture(description, material, "specularColor", "_SPECULAR_COLOR");
            remapPropertyFloatOrTexture(description, material, "specularRoughness", "_SPECULAR_ROUGHNESS");
            remapPropertyFloatOrTexture(description, material, "specularIOR", "_SPECULAR_IOR");
            remapPropertyFloatOrTexture(description, material, "specularAnisotropy", "_SPECULAR_ANISOTROPY");
            remapPropertyFloatOrTexture(description, material, "specularRotation", "_SPECULAR_ROTATION");

            remapPropertyTexture(description, material, "normalCamera", "_NORMAL_MAP");

            remapPropertyFloat(description, material, "coat", "_COAT_WEIGHT");
            remapPropertyColorOrTexture(description, material, "coatColor", "_COAT_COLOR");
            remapPropertyFloatOrTexture(description, material, "coatRoughness", "_COAT_ROUGHNESS");
            remapPropertyFloatOrTexture(description, material, "coatIOR", "_COAT_IOR");
            remapPropertyTexture(description, material, "coatNormal", "_COAT_NORMAL");
        }
        /// <summary>
        /// Load content for the screen.
        /// </summary>
        /// <param name="GraphicInfo"></param>
        /// <param name="factory"></param>
        /// <param name="contentManager"></param>
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            ///Uncoment to add your model
            SimpleModel simpleModel = new SimpleModel(factory, "Model/cenario");
            ///Physic info (position, rotation and scale are set here)
            TriangleMeshObject tmesh = new TriangleMeshObject(simpleModel, Vector3.Zero, Matrix.Identity, Vector3.One, MaterialDescription.DefaultBepuMaterial());
            ///Forward Shader (look at this shader construction for more info)
            ForwardXNABasicShader shader = new ForwardXNABasicShader();
            ///Forward material
            ForwardMaterial fmaterial = new ForwardMaterial(shader);
            ///The object itself
            IObject obj = new IObject(fmaterial, simpleModel, tmesh);

            ///Add to the world
            this.World.AddObject(obj);

            this.RenderTechnic.AddPostEffect(MotionBlurPostEffect);
            this.RenderTechnic.AddPostEffect(BloomPostEffect);

            BloomPostEffect.Enabled      = false;
            MotionBlurPostEffect.Enabled = false;

            blurdefault = MotionBlurPostEffect.Amount;

            RotatingCamera cam = new RotatingCamera(this, new Vector3(0, -100, -400));

            this.World.CameraManager.AddCamera(cam);

            RasterizerState          = new RasterizerState();
            RasterizerState.CullMode = CullMode.None;
        }
        protected override void LoadContent(PloobsEngine.Engine.GraphicInfo GraphicInfo, PloobsEngine.Engine.GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            #region Models
            ///Cria um modelo Controlavel pelo teclado
            {
                SimpleModel sm = new SimpleModel(factory, "..\\Content\\Model\\cubo");
                sm.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Blue), TextureType.DIFFUSE);

                DeferredNormalShader shader = new DeferredNormalShader();

                IMaterial mat = new DeferredMaterial(shader);
                CharacterControllerInput character = new CharacterControllerInput(this, new Vector3(100, 150, 1), 1, 1, 50, Vector3.One * 10, 0.5f);

                character.AheadKey = Keys.G;
                character.BackKey  = Keys.T;
                character.LeftKey  = Keys.F;
                character.RightKey = Keys.H;
                character.JumpKey  = Keys.R;
                character.Characterobj.CharacterController.MaxSpeed  = 35f;
                character.Characterobj.CharacterController.JumpSpeed = 15f;
                player = new IObject(mat, sm, character.Characterobj);
                this.World.AddObject(player);
            }

            ///Cria o cenario padrao de sempre ;)
            {
                SimpleModel sm = new SimpleModel(factory, "..\\Content\\Model\\cenario");

                IPhysicObject        pi     = new TriangleMeshObject(sm, Vector3.Zero, Matrix.Identity, Vector3.One, MaterialDescription.DefaultBepuMaterial());
                DeferredNormalShader shader = new DeferredNormalShader();
                IMaterial            mat    = new DeferredMaterial(shader);
                IObject obj3 = new IObject(mat, sm, pi);
                this.World.AddObject(obj3);
            }

            #endregion

            #region Cameras

            cam0 = new CameraFollowObject(player);
            ///Dando um nome a ela (para poder recupera-la depois)
            cam0.Name     = "follow";
            cam0.FarPlane = 3000;
            ///Adiciona ao Manager (NAO ESTA SENDO ATIVADA, APENAS ADICIONADA)
            this.World.CameraManager.AddCamera(cam0, cam0.Name);
            ///Ativa a camera atual (AO ADICIONAR UMA CAMERA AO WORLD USANDO mundo.AddCamera(cam) A CAMERA EH AUTOMATICAMENTE ATIVADA  )
            this.World.CameraManager.SetActiveCamera(cam0.Name);
            ///Adiciona na lista circular
            camerasNames.Value = cam0.Name;
            camerasNames.Next();

            cam1 = new CameraFirstPerson(GraphicInfo);
            ///Dando um nome a ela (para poder recupera-la depois)
            cam1.Name     = "first person";
            cam1.FarPlane = 3000;
            ///Adiciona ao Manager (NAO ESTA SENDO ATIVADA, APENAS ADICIONADA)
            this.World.CameraManager.AddCamera(cam1, cam1.Name);
            ///Ativa a camera atual (AO ADICIONAR UMA CAMERA AO WORLD USANDO mundo.AddCamera(cam) A CAMERA EH AUTOMATICAMENTE ATIVADA  )
            this.World.CameraManager.SetActiveCamera(cam1.Name);
            ///Adiciona na lista circular
            camerasNames.Value = cam1.Name;
            //camerasNames.Next();

            #endregion

            ///Objeto que permite atirar bolas de luzes na cena
            lt = new LightThrowBepu(this.World, factory);

            #region NormalLight
            ///Conjunto de luzes direcionais
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.4f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion

            {
                SimpleConcreteKeyboardInputPlayable ik = new SimpleConcreteKeyboardInputPlayable(StateKey.PRESS, Keys.Space, ChangeCamera);
                BindKeyCommand bk = new BindKeyCommand(ik, BindAction.ADD);
                CommandProcessor.getCommandProcessor().SendCommandAssyncronous(bk);
            }
        }
        void CreateFromStandardMaterial(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var shader = Shader.Find("Standard");

            if (shader == null)
            {
                context.LogImportError("ThreeDSMaterialDescriptionPreprocessor cannot find a shader named 'Standard'.");
                return;
            }
            material.shader = shader;

            Vector4 vectorProperty;
            float   floatProperty;
            TexturePropertyDescription textureProperty;

            bool isTransparent = false;

            float opacity;
            float transparencyFactor;

            if (!description.TryGetProperty("Opacity", out opacity))
            {
                if (description.TryGetProperty("TransparencyFactor", out transparencyFactor))
                {
                    opacity = transparencyFactor == 1.0f ? 1.0f : 1.0f - transparencyFactor;
                }
                if (opacity == 1.0f && description.TryGetProperty("TransparentColor", out vectorProperty))
                {
                    opacity = vectorProperty.x == 1.0f ? 1.0f : 1.0f - vectorProperty.x;
                }
            }
            if (opacity < 1.0f || (opacity == 1.0f && description.TryGetProperty("TransparentColor", out textureProperty)))
            {
                isTransparent = true;
            }
            else if (description.HasAnimationCurve("TransparencyFactor") || description.HasAnimationCurve("TransparentColor"))
            {
                isTransparent = true;
            }

            if (isTransparent)
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Transparent);
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Opaque);
                material.SetOverrideTag("RenderType", "");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
            }

            if (description.TryGetProperty("DiffuseColor", out textureProperty))
            {
                Color diffuseColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
                if (description.TryGetProperty("DiffuseFactor", out floatProperty))
                {
                    diffuseColor *= floatProperty;
                }
                diffuseColor.a = opacity;

                SetMaterialTextureProperty("_MainTex", material, textureProperty);
                material.SetColor("_Color", PlayerSettings.colorSpace == ColorSpace.Gamma ? diffuseColor.gamma : diffuseColor);
            }
            else if (description.TryGetProperty("DiffuseColor", out vectorProperty))
            {
                Color diffuseColor = vectorProperty;
                if (description.TryGetProperty("DiffuseFactor", out floatProperty))
                {
                    diffuseColor *= floatProperty;
                }
                diffuseColor.a = opacity;
                material.SetColor("_Color", PlayerSettings.colorSpace == ColorSpace.Gamma ? diffuseColor.gamma : diffuseColor);
            }

            if (description.TryGetProperty("Bump", out textureProperty))
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                material.EnableKeyword("_NORMALMAP");

                if (description.TryGetProperty("BumpFactor", out floatProperty))
                {
                    material.SetFloat("_BumpScale", floatProperty);
                }
            }
            else if (description.TryGetProperty("NormalMap", out textureProperty))
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                material.EnableKeyword("_NORMALMAP");

                if (description.TryGetProperty("BumpFactor", out floatProperty))
                {
                    material.SetFloat("_BumpScale", floatProperty);
                }
            }

            if (description.TryGetProperty("EmissiveColor", out textureProperty))
            {
                Color emissiveColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);

                material.SetColor("_EmissionColor", emissiveColor);
                SetMaterialTextureProperty("_EmissionMap", material, textureProperty);

                if (description.TryGetProperty("EmissiveFactor", out floatProperty) && floatProperty > 0.0f)
                {
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
            }
            else if (
                description.TryGetProperty("EmissiveColor", out vectorProperty) && vectorProperty.magnitude > vectorProperty.w ||
                description.HasAnimationCurve("EmissiveColor.x"))
            {
                if (description.TryGetProperty("EmissiveFactor", out floatProperty))
                {
                    vectorProperty *= floatProperty;
                }

                material.SetColor("_EmissionColor", vectorProperty);
                if (floatProperty > 0.0f)
                {
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
            }

            material.SetFloat("_Glossiness", 0.0f);

            if (PlayerSettings.colorSpace == ColorSpace.Gamma)
            {
                RemapAndTransformColorCurves(description, clips, "DiffuseColor", "_Color", ConvertFloatLinearToGamma);
            }
            else
            {
                RemapColorCurves(description, clips, "DiffuseColor", "_Color");
            }

            RemapTransparencyCurves(description, clips);

            RemapColorCurves(description, clips, "EmissiveColor", "_EmissionColor");
        }
Ejemplo n.º 29
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            CameraFirstPerson CameraFirstPerson = new CameraFirstPerson(true, GraphicInfo);

            Texture2D   tMap = factory.GetTexture2D("Textures//hmap_10243");
            QuadTerrain q    = new PloobsEngine.Material.QuadTerrain(factory, tMap, 33, 513, 10, 3f);

            DeferredTerrainMaterial mat = new DeferredTerrainMaterial(q);

            //Set various terrain stats.
            mat.diffuseScale      = q.flatScale / 4;
            mat.detailScale       = q.flatScale / 100;
            mat.detailMapStrength = 2;
            mat.textureBlend      = factory.GetTexture2D("Textures//hmap_256blend");
            mat.textureDetail     = factory.GetTexture2D("Textures//coolgrass2DOT3");
            mat.textureRed        = factory.GetTexture2D("Textures//TexR");
            mat.textureGreen      = factory.GetTexture2D("Textures//TexG");
            mat.textureBlue       = factory.GetTexture2D("Textures//TexB");
            mat.textureBlack      = factory.GetTexture2D("Textures//TexBase");

            TerrainObject to = new TerrainObject(factory, Vector3.Zero, Matrix.Identity, q.getHeightMap(), MaterialDescription.DefaultBepuMaterial());

            IObject obj3 = new IObject(mat, null, to);

            this.World.AddObject(obj3);

            LightThrowBepu lt = new LightThrowBepu(this.World, factory);

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            this.World.CameraManager.AddCamera(CameraFirstPerson);
            CameraFirstPerson.FarPlane = 20000;

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//cubemap");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
        static bool IsAutodeskInteractiveMaterial(MaterialDescription description)
        {
            string stringValue;

            return(description.TryGetProperty("renderAPI", out stringValue) && stringValue == "SFX_PBS_SHADER");
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Create a Terrain Physic Object
        /// </summary>
        /// <param name="gfactory">The gfactory.</param>
        /// <param name="heighmapName">Name of the heighmap texture</param>
        /// <param name="translation">The translation.</param>
        /// <param name="rotation">The rotation.</param>
        /// <param name="materialDesc">The material desc.</param>
        /// <param name="XSpacing">The X spacing.</param>
        /// <param name="ZSpacing">The Z spacing.</param>
        /// <param name="heightMultipler">Default 10 - controla a altura, menor mais alto</param>
        public TerrainObject(GraphicFactory gfactory, String heighmapName, Vector3 translation, Matrix?rotation = null, MaterialDescription materialDesc = null, float XSpacing = 1, float ZSpacing = 1, float heightMultipler = 10)
        {
            if (!rotation.HasValue)
            {
                rotation = Matrix.Identity;
            }

            if (materialDecription == null)
            {
                materialDecription = MaterialDescription.DefaultBepuMaterial();
            }


            //Used to calculate ther proportion of the xNormalized in the getHeightFast method
            xScale = XSpacing;
            zScale = ZSpacing;


            this.heightMultipler = heightMultipler;
            this.image           = heighmapName;

            sourceImage = gfactory.GetTexture2D(image);
            int xLength = sourceImage.Width;
            int yLength = sourceImage.Height;

            terrainWidth  = xLength;
            terrainHeight = yLength;


            this.rotation = rotation.Value;
            //this.scale = scale;

            Color[] colorData = new Color[xLength * yLength];
            sourceImage.GetData <Color>(colorData);

            var heightStore = new float[xLength, yLength];

            for (int i = 0; i < xLength; i++)
            {
                for (int j = 0; j < yLength; j++)
                {
                    Color color = colorData[j * xLength + i];
                    heightStore[i, j] = (color.R) / heightMultipler;

                    if (heightStore[i, j] > maxHeight)
                    {
                        maxHeight = heightStore[i, j];
                    }
                    if (heightStore[i, j] < minHeight)
                    {
                        minHeight = heightStore[i, j];
                    }
                }
            }
            //Create the terrain.
            BEPUphysics.CollisionShapes.TerrainShape shape = new BEPUphysics.CollisionShapes.TerrainShape(heightStore, BEPUphysics.CollisionShapes.QuadTriangleOrganization.BottomLeftUpperRight);

            terrain = new Terrain(shape, new BEPUphysics.MathExtensions.AffineTransform(new Vector3(XSpacing, 1, ZSpacing), Quaternion.CreateFromRotationMatrix(rotation.Value), new Vector3(-xLength * XSpacing / 2, 0, -yLength * ZSpacing / 2) + translation));
            terrain.ImproveBoundaryBehavior = true;

            SetMaterialDescription(materialDesc);
        }
Ejemplo n.º 32
0
        public static IObject[] CreateOBJ(IWorld world, GraphicFactory factory, GraphicInfo ginfo, ObjectInformation[] mi)
        {
            IModelo model = new CustomModel(factory, mi);

            MaterialDescription material;

            if (mi[0].staticfriction == -1 || mi[0].dinamicfriction == -1 || mi[0].ellasticity == -1)
            {
                material = MaterialDescription.DefaultBepuMaterial();
            }
            else
            {
                material = new MaterialDescription(mi[0].staticfriction, mi[0].dinamicfriction, mi[0].ellasticity);
            }

            IPhysicObject po;

            bool massflag = false;

            if (mi[0].mass == 0)
            {
                massflag   = true;
                mi[0].mass = 0.5f;
            }

            BatchInformation binf = model.GetBatchInformation(0)[0];

            BoundingBox bb;

            switch (mi[0].collisionType)
            {
            case "Ghost":


                po = new GhostObject(mi[0].position, Matrix.CreateFromQuaternion(mi[0].rotation), mi[0].scale);

                break;

            case "Cylinder":

                binf.ModelLocalTransformation = Matrix.Identity;
                bb = ModelBuilderHelper.CreateBoundingBoxFromModel(binf);
                Vector3 len = bb.Max - bb.Min;

                po = new CylinderObject(mi[0].position, len.Y, len.X / 2, Vector3.Up, mi[0].mass, Matrix.CreateFromQuaternion(mi[0].rotation), material);

                break;


            case "Sphere":
                binf.ModelLocalTransformation = Matrix.Identity;
                po          = new SphereObject(mi[0].position, model.GetModelRadius(), mi[0].mass, mi[0].scale.X, material);
                po.Rotation = Matrix.CreateFromQuaternion(mi[0].rotation);

                break;


            case "Box":

                bb = ModelBuilderHelper.CreateBoundingBoxFromModel(binf);

                len = bb.Max - bb.Min;

                po = new BoxObject(mi[0].position, len.X, len.Y, len.Z, mi[0].mass, mi[0].scale, Matrix.CreateFromQuaternion(mi[0].rotation), material);

                break;

            case "Water":
                po = new GhostObject(mi[0].position, Matrix.CreateFromQuaternion(mi[0].rotation), mi[0].scale);
                break;

            case "TriangleMesh":
            default:
                po = new TriangleMeshObject(model, Vector3.Zero, Matrix.Identity, new Vector3(1), material);
                break;
            }

            po.isMotionLess = massflag;

            IShader shader = null;

#if !REACH && !WINDOWS_PHONE
            if (mi[0].HasTexture(TextureType.ENVIRONMENT))
            {
                shader = new DeferredEMReflectiveShader();
                (shader as DeferredEMReflectiveShader).TextureCube = mi[0].textureInformation.getCubeTexture(TextureType.ENVIRONMENT);
            }
            else if (mi[0].collisionType != null && mi[0].collisionType.Contains("Water"))
            {
                Vector3 position = (Vector3)(mi[0].extra["position"]);
                var     width    = (mi[0].extra["width"]);
                var     height   = (mi[0].extra["length"]);
                shader = new DeferredWaterCompleteShader((int)width, (int)height, new Plane(position.X, position.Y, position.Z, 1), 10.0f);
            }

            else
            {
                shader = new DeferredCustomShader(mi[0].HasTexture(TextureType.GLOW), mi[0].HasTexture(TextureType.BUMP), mi[0].HasTexture(TextureType.SPECULAR), mi[0].HasTexture(TextureType.PARALAX));
            }

            DeferredMaterial dm = new DeferredMaterial(shader);
#else
            shader = new ForwardXNABasicShader();
            ForwardMaterial dm = new ForwardMaterial(shader);
#endif
            IObject ob = new IObject(dm, model, po);

            ob.Name = mi[0].modelName;

            return(new IObject[] { ob });
        }
Ejemplo n.º 33
0
        public void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var pipelineAsset = GraphicsSettings.currentRenderPipeline;

            if (!pipelineAsset || pipelineAsset.GetType() != typeof(HDRenderPipelineAsset))
            {
                return;
            }

            var lowerCasePath = Path.GetExtension(assetPath).ToLower();

            if (lowerCasePath != ".3ds")
            {
                return;
            }

            var shader = Shader.Find("HDRP/Lit");

            if (shader == null)
            {
                return;
            }
            material.shader = shader;

            material.SetShaderPassEnabled("DistortionVectors", false);
            material.SetShaderPassEnabled("TransparentDepthPrepass", false);
            material.SetShaderPassEnabled("TransparentDepthPostpass", false);
            material.SetShaderPassEnabled("TransparentBackface", false);
            material.SetShaderPassEnabled("MOTIONVECTORS", false);

            TexturePropertyDescription textureProperty;
            float   floatProperty;
            Vector4 vectorProperty;

            description.TryGetProperty("diffuse", out vectorProperty);
            vectorProperty.x /= 255.0f;
            vectorProperty.y /= 255.0f;
            vectorProperty.z /= 255.0f;
            vectorProperty.w /= 255.0f;
            description.TryGetProperty("transparency", out floatProperty);

            bool isTransparent = vectorProperty.w <= 0.99f || floatProperty > .0f;

            if (isTransparent)
            {
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.SetFloat("_BlendMode", (float)BlendMode.Alpha);
                material.SetFloat("_EnableBlendModePreserveSpecularLighting", 1.0f);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
                material.EnableKeyword("_ENABLE_FOG_ON_TRANSPARENT");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.renderQueue = -1;
            }

            if (floatProperty > .0f)
            {
                vectorProperty.w = 1.0f - floatProperty;
            }

            Color diffuseColor = vectorProperty;

            material.SetColor("_Color", PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor);
            material.SetColor("_BaseColor", PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor);

            if (description.TryGetProperty("EmissiveColor", out vectorProperty))
            {
                material.SetColor("_EmissionColor", vectorProperty);
                material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                material.EnableKeyword("_EMISSION");
            }

            if (description.TryGetProperty("texturemap1", out textureProperty))
            {
                SetMaterialTextureProperty("_MainTex", material, textureProperty);
                SetMaterialTextureProperty("_BaseColorMap", material, textureProperty);
            }

            if (description.TryGetProperty("bumpmap", out textureProperty) && textureProperty.texture != null)
            {
                if (material.HasProperty("_BumpMap"))
                {
                    SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                    material.EnableKeyword("_NORMALMAP_TANGENT_SPACE");
                }
            }
        }
Ejemplo n.º 34
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            SimpleModel simpleModel = new SimpleModel(factory, "Model//block");

            simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.White), TextureType.DIFFUSE);
            BoxObject tmesh = new BoxObject(new Vector3(0, 10, 0), 1, 1, 1, 50, new  Vector3(5000, 1, 5000), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());

            tmesh.isMotionLess = true;
            DeferredNormalShader shader    = new DeferredNormalShader();
            DeferredMaterial     fmaterial = new DeferredMaterial(shader);
            IObject obj = new IObject(fmaterial, simpleModel, tmesh);

            this.World.AddObject(obj);

            {
                List <BilboardInstance> poss = new List <BilboardInstance>();
                for (int i = -10; i < 20; i++)
                {
                    for (int j = -10; j < 20; j++)
                    {
                        float x, y;
                        x = i * 100;
                        y = j * 100;
                        BilboardInstance bi = new BilboardInstance();
                        bi.Scale    = new Vector2(100, 100);
                        bi.Position = new Vector3(x, 5, y);
                        poss.Add(bi);
                    }
                }

                ///same as before, just the name of the class change
                ///You can change the position of a individual bilboard using bm.GetBilboardInstances(), updating the structure recieved and
                ///using bm.SetBilboardInstances(). Dont do this every frame pls =P
                ///You can change lots of parameters of the DeferredInstancedBilboardShader, check it
                InstancedBilboardModel          bm = new InstancedBilboardModel(factory, "Bilbs", "..\\Content\\Textures\\tree", poss.ToArray());
                DeferredInstancedBilboardShader cb = new DeferredInstancedBilboardShader(BilboardType.Cilindric);
                DeferredMaterial matfor            = new DeferredMaterial(cb);
                GhostObject      go   = new GhostObject();
                IObject          obj2 = new IObject(matfor, bm, go);
                this.World.AddObject(obj2);
            }


            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            CameraFirstPerson cam = new CameraFirstPerson(MathHelper.ToRadians(-50), MathHelper.ToRadians(-15), new Vector3(-200, 300, 250), GraphicInfo);
            this.World.CameraManager.AddCamera(cam);

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//grassCube");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
Ejemplo n.º 35
0
 void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] materialAnimation)
 {
 }
        public void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var pipelineAsset = GraphicsSettings.currentRenderPipeline;

            if (!pipelineAsset || pipelineAsset.GetType() != typeof(UniversalRenderPipelineAsset))
            {
                return;
            }

            var lowerCasePath = Path.GetExtension(assetPath).ToLower();

            if (lowerCasePath != ".3ds")
            {
                return;
            }

            string path   = AssetDatabase.GUIDToAssetPath(ShaderUtils.GetShaderGUID(ShaderPathID.Lit));
            var    shader = AssetDatabase.LoadAssetAtPath <Shader>(path);

            if (shader == null)
            {
                return;
            }
            material.shader = shader;

            TexturePropertyDescription textureProperty;
            float   floatProperty;
            Vector4 vectorProperty;

            description.TryGetProperty("diffuse", out vectorProperty);
            vectorProperty.x /= 255.0f;
            vectorProperty.y /= 255.0f;
            vectorProperty.z /= 255.0f;
            vectorProperty.w /= 255.0f;
            description.TryGetProperty("transparency", out floatProperty);

            bool isTransparent = vectorProperty.w <= 0.99f || floatProperty > .0f;

            if (isTransparent)
            {
                material.SetFloat("_Mode", (float)3.0); // From C# enum BlendMode
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
                material.SetInt("_Surface", 1);
            }
            else
            {
                material.SetFloat("_Mode", (float)0.0); // From C# enum BlendMode
                material.SetOverrideTag("RenderType", "");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
                material.SetInt("_Surface", 0);
            }

            if (floatProperty > .0f)
            {
                vectorProperty.w = 1.0f - floatProperty;
            }

            Color diffuseColor = vectorProperty;

            material.SetColor("_Color", PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor);
            material.SetColor("_BaseColor", PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor);

            if (description.TryGetProperty("EmissiveColor", out vectorProperty))
            {
                material.SetColor("_EmissionColor", vectorProperty);
                material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                material.EnableKeyword("_EMISSION");
            }

            if (description.TryGetProperty("texturemap1", out textureProperty))
            {
                SetMaterialTextureProperty("_BaseMap", material, textureProperty);
            }

            if (description.TryGetProperty("bumpmap", out textureProperty))
            {
                if (material.HasProperty("_BumpMap"))
                {
                    SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                    material.EnableKeyword("_NORMALMAP");
                }
            }
        }
 static void PreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] animations)
 {
     object[] args = { description, material, animations };
     CallPostProcessMethods("OnPreprocessMaterialDescription", args);
 }
Ejemplo n.º 38
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            IObject            marine;
            AnimatedController marinecontroler;
            {
                ///carrega o Modelo
                AnimatedModel am = new AnimatedModel(factory, "..\\Content\\Model\\PlayerMarine", "..\\Content\\Textures\\PlayerMarineDiffuse");
                ///Inicializa o Controlador (Idle eh o nome da animacao inicial)
                marinecontroler = new AnimatedController(am, "Idle");

                ///Cria o shader e o material animados
                ForwardSimpleAnimationShader sas  = new ForwardSimpleAnimationShader(marinecontroler);
                ForwardAnimatedMaterial      amat = new ForwardAnimatedMaterial(marinecontroler, sas);
                marine = new IObject(amat, am, new GhostObject(new Vector3(0, -30, 0), Matrix.CreateRotationX(MathHelper.ToRadians(30)), Vector3.One * 0.4f));

                ///Adiciona no mundo
                this.World.AddObject(marine);

                CharacterControllerInput gp = new CharacterControllerInput(this, new Vector3(100, 50, 1), 25, 10, 10, Vector3.One);
                marine = new IObject(amat, am, gp.Characterobj);
                ///Adiciona no mundo
                this.World.AddObject(marine);
            }

            {
                ///carrega o Modelo
                AnimatedModel am = new AnimatedModel(factory, "..\\Content\\Model\\WeaponMachineGun", "..\\Content\\Textures\\WeaponMachineGunDiffuse");
                ///Inicializa o Controlador (Idle eh o nome da animacao inicial)
                AnimatedController arobo = new AnimatedController(am);
                //arobo.isLoop = true;

                ///Cria o shader e o material animados
                ForwardSimpleAnimationShader sas  = new ForwardSimpleAnimationShader(arobo, marine, marinecontroler, "R_Hand2");
                ForwardAnimatedMaterial      amat = new ForwardAnimatedMaterial(arobo, sas);
                IObject gun = new IObject(amat, am, new GhostObject(new Vector3(0, 0, 0), Matrix.Identity, Vector3.One));

                ///Adiciona no mundo
                this.World.AddObject(gun);
            }

            {
                SimpleModel           simpleModel = new SimpleModel(factory, "Model//cenario");
                TriangleMeshObject    tmesh       = new TriangleMeshObject(simpleModel, Vector3.Zero, Matrix.Identity, Vector3.One, MaterialDescription.DefaultBepuMaterial());
                ForwardXNABasicShader shader      = new ForwardXNABasicShader();
                ForwardMaterial       fmaterial   = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, tmesh);
                this.World.AddObject(obj);
            }


            CameraFirstPerson cam = new CameraFirstPerson(MathHelper.ToRadians(-60), MathHelper.ToRadians(-20), new Vector3(30, 50, 50), GraphicInfo);

            cam.MoveSpeed *= 5;
            this.World.CameraManager.AddCamera(cam);

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//grasscube");

            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
Ejemplo n.º 39
0
 public MaterialParametersVisitor(MaterialDescription mat)
     : base(mat)
 {
 }
Ejemplo n.º 40
0
 public MaterialParametersCreator(MaterialDescription mat, string assetUrl) : base(mat)
 {
     Parameters  = new ParameterCollectionData();
     materialUrl = assetUrl;
 }
Ejemplo n.º 41
0
        protected override void LoadContent(PloobsEngine.Engine.GraphicInfo GraphicInfo, PloobsEngine.Engine.GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            Picking picking = new Picking(this);

            this.AddScreenUpdateable(picking);

            #region Models
            {
                SimpleModel          sm     = new SimpleModel(factory, "..\\Content\\Model\\cenario");
                IPhysicObject        pi     = new TriangleMeshObject(sm, Vector3.Zero, Matrix.Identity, Vector3.One, MaterialDescription.DefaultBepuMaterial());
                DeferredNormalShader shader = new DeferredNormalShader();
                IMaterial            mat    = new DeferredMaterial(shader);
                IObject obj3 = new IObject(mat, sm, pi);
                obj3.Name = "cenario";
                this.World.AddObject(obj3);
            }

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    SimpleModel sm = new SimpleModel(factory, "..\\Content\\Model\\cubo");
                    sm.SetTexture(factory.CreateTexture2DColor(1, 1, Color.White), TextureType.DIFFUSE);
                    BoxObject pi = new BoxObject(new Vector3(i * 10, 100, j * 10), 1, 1, 1, 1, new Vector3(5), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());
                    pi.isMotionLess = true;
                    DeferredNormalShader shader = new DeferredNormalShader();
                    IMaterial            mat    = new DeferredMaterial(shader);
                    IObject obj4 = new IObject(mat, sm, pi);
                    obj4.Name = "Block " + i + " : " + j;
                    this.World.AddObject(obj4);
                }
            }

            #endregion

            cam          = new CameraFirstPerson(GraphicInfo);
            cam.FarPlane = 3000;

            #region NormalLight
            ///Conjunto de luzes direcionais
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.4f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            this.World.CameraManager.AddCamera(cam);


            ///O PICKING FUNCIONA APENAS COM OBJETOS QUE TENHAM CORPO FISICO REAL !!!
            ///OS GHOST E OS DUMMY NUNCA SERAO SELECIONADOS
            ///Para ser informado a todo frame sobre as colisoes do raio, basta utilizar o outro construtor
            picking.OnPickedLeftButton += new OnPicked(onPick);
        }
Ejemplo n.º 42
0
        public void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var pipelineAsset = GraphicsSettings.currentRenderPipeline;

            if (!pipelineAsset || pipelineAsset.GetType() != typeof(UniversalRenderPipelineAsset))
            {
                return;
            }

            var lowerCasePath = Path.GetExtension(assetPath).ToLower();

            if (lowerCasePath != ".skp")
            {
                return;
            }

            string path   = AssetDatabase.GUIDToAssetPath(ShaderUtils.GetShaderGUID(ShaderPathID.Lit));
            var    shader = AssetDatabase.LoadAssetAtPath <Shader>(path);

            if (shader == null)
            {
                return;
            }
            material.shader = shader;

            float   floatProperty;
            Vector4 vectorProperty;
            TexturePropertyDescription textureProperty;

            if (description.TryGetProperty("DiffuseMap", out textureProperty) && textureProperty.texture != null)
            {
                SetMaterialTextureProperty("_BaseMap", material, textureProperty);
                SetMaterialTextureProperty("_MainTex", material, textureProperty);
                var color = new Color(1.0f, 1.0f, 1.0f, 1.0f);
                material.SetColor("_BaseColor", color);
                material.SetColor("_Color", color);
            }
            else if (description.TryGetProperty("DiffuseColor", out vectorProperty))
            {
                Color diffuseColor = vectorProperty;
                diffuseColor = PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor;
                material.SetColor("_BaseColor", diffuseColor);
                material.SetColor("_Color", diffuseColor);
            }

            if (description.TryGetProperty("IsTransparent", out floatProperty) && floatProperty == 1.0f)
            {
                material.SetFloat("_Mode", (float)3.0); // From C# enum BlendMode
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
                material.SetInt("_Surface", 1);
            }
            else
            {
                material.SetFloat("_Mode", (float)0.0); // From C# enum BlendMode
                material.SetOverrideTag("RenderType", "");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
                material.SetInt("_Surface", 0);
            }
        }
 /// <summary>
 /// Sets the material description.
 /// </summary>
 /// <param name="materialDescription">The material description.</param>
 public void SetMaterialDescription(MaterialDescription materialDescription)
 {
     System.Diagnostics.Debug.Assert(materialDescription != null);
     this.materialDecription = materialDescription;
     entity.Material = new BEPUphysics.Materials.Material(materialDescription.StaticFriction, materialDescription.DynamicFriction, materialDescription.Bounciness);
 }
Ejemplo n.º 44
0
        public void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var pipelineAsset = GraphicsSettings.currentRenderPipeline;

            if (!pipelineAsset || pipelineAsset.GetType() != typeof(HDRenderPipelineAsset))
            {
                return;
            }

            var lowerCaseExtension = Path.GetExtension(assetPath).ToLower();

            if (lowerCaseExtension != ".fbx" && lowerCaseExtension != ".obj" && lowerCaseExtension != ".dae" && lowerCaseExtension != ".obj" && lowerCaseExtension != ".blend" && lowerCaseExtension != ".mb" && lowerCaseExtension != ".ma" && lowerCaseExtension != ".max")
            {
                return;
            }

            var shader = AssetDatabase.LoadAssetAtPath <Shader>(k_ShaderPath);

            if (shader == null)
            {
                return;
            }

            material.shader = shader;

            material.SetShaderPassEnabled("DistortionVectors", false);
            material.SetShaderPassEnabled("TransparentDepthPrepass", false);
            material.SetShaderPassEnabled("TransparentDepthPostpass", false);
            material.SetShaderPassEnabled("TransparentBackface", false);
            material.SetShaderPassEnabled("MOTIONVECTORS", false);

            Vector4 vectorProperty;
            float   floatProperty;
            TexturePropertyDescription textureProperty;

            bool isTransparent = false;

            float opacity;
            float transparencyFactor;

            if (!description.TryGetProperty("Opacity", out opacity))
            {
                if (description.TryGetProperty("TransparencyFactor", out transparencyFactor))
                {
                    opacity = transparencyFactor == 1.0f ? 1.0f : 1.0f - transparencyFactor;
                }
                if (opacity == 1.0f && description.TryGetProperty("TransparentColor", out vectorProperty))
                {
                    opacity = vectorProperty.x == 1.0f ? 1.0f : 1.0f - vectorProperty.x;
                }
            }
            if (opacity < 1.0f || (opacity == 1.0f && description.TryGetProperty("TransparentColor", out textureProperty)))
            {
                isTransparent = true;
            }
            else if (description.HasAnimationCurve("TransparencyFactor") || description.HasAnimationCurve("TransparentColor"))
            {
                isTransparent = true;
            }

            if (isTransparent)
            {
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.SetFloat("_BlendMode", (float)BlendMode.Alpha);
                material.SetFloat("_EnableBlendModePreserveSpecularLighting", 1.0f);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
                material.EnableKeyword("_ENABLE_FOG_ON_TRANSPARENT");
                material.EnableKeyword("_ALPHATEST_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
                material.SetFloat("_SurfaceType", 1.0f);
                material.SetFloat("_Cutoff", .0f);
                material.SetFloat("_AlphaCutoffEnable", 1.0f);
                material.SetFloat("_AlphaCutoff", .0f);
                material.SetFloat("_AlphaCutoffShadow", 1.0f);
                material.SetFloat("_UseShadowThreshold", 1.0f);
            }
            else
            {
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.renderQueue = -1;
            }

            if (description.TryGetProperty("DiffuseColor", out textureProperty) && textureProperty.texture != null)
            {
                Color diffuseColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
                if (description.TryGetProperty("DiffuseFactor", out floatProperty))
                {
                    diffuseColor *= floatProperty;
                }
                diffuseColor.a = opacity;

                SetMaterialTextureProperty("_BaseColorMap", material, textureProperty);
                material.SetColor("_BaseColor", diffuseColor);
            }
            else if (description.TryGetProperty("DiffuseColor", out vectorProperty))
            {
                Color diffuseColor = vectorProperty;
                if (description.TryGetProperty("DiffuseFactor", out floatProperty))
                {
                    diffuseColor *= floatProperty;
                }
                diffuseColor.a = opacity;
                material.SetColor("_BaseColor", PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor);
            }

            if (description.TryGetProperty("Bump", out textureProperty) && textureProperty.texture != null)
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                material.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

                if (description.TryGetProperty("BumpFactor", out floatProperty))
                {
                    material.SetFloat("_BumpScale", floatProperty);
                }
            }
            else if (description.TryGetProperty("NormalMap", out textureProperty) && textureProperty.texture != null)
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                material.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

                if (description.TryGetProperty("BumpFactor", out floatProperty))
                {
                    material.SetFloat("_BumpScale", floatProperty);
                }
            }
            else
            {
                material.DisableKeyword("_NORMALMAP");
            }

            if (description.TryGetProperty("EmissiveColor", out textureProperty))
            {
                Color emissiveColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);

                material.SetColor("_EmissionColor", emissiveColor);
                material.SetColor("_EmissiveColor", emissiveColor);
                SetMaterialTextureProperty("_EmissionMap", material, textureProperty);

                if (description.TryGetProperty("EmissiveFactor", out floatProperty) && floatProperty > 0.0f)
                {
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
            }
            else if (description.TryGetProperty("EmissiveColor", out vectorProperty) && vectorProperty.magnitude > vectorProperty.w ||
                     description.HasAnimationCurve("EmissiveColor.x"))
            {
                if (description.TryGetProperty("EmissiveFactor", out floatProperty))
                {
                    vectorProperty *= floatProperty;
                }

                material.SetColor("_EmissionColor", vectorProperty);
                material.SetColor("_EmissiveColor", vectorProperty);
                if (floatProperty > 0.0f)
                {
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
            }

            material.SetFloat("_Glossiness", 0.0f);

            if (PlayerSettings.colorSpace == ColorSpace.Linear)
            {
                RemapAndTransformColorCurves(description, clips, "DiffuseColor", "_BaseColor", ConvertFloatLinearToGamma);
            }
            else
            {
                RemapColorCurves(description, clips, "DiffuseColor", "_BaseColor");
            }

            RemapTransparencyCurves(description, clips);

            RemapColorCurves(description, clips, "EmissiveColor", "_EmissionColor");
            RemapColorCurves(description, clips, "EmissiveColor", "_EmissiveColor");
        }
        void CreateFrom3DsMaxArnoldStandardSurfaceMaterial(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            // 3DsMax does not export material animations for Arnold materials.
            var shader = Shader.Find("Autodesk Interactive");

            if (shader == null)
            {
                context.LogImportError("ThreeDSMaterialDescriptionPreprocessor cannot find a shader named 'Autodesk Interactive'.");
                return;
            }
            material.shader = shader;

            float   floatProperty;
            Vector4 vectorProperty;
            TexturePropertyDescription textureProperty;

            if (description.TryGetProperty("transmission", out floatProperty) && floatProperty > 0.0f)
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Transparent);
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetInt("_Mode", (int)StandardShaderGUI.BlendMode.Opaque);
                material.SetOverrideTag("RenderType", "");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
            }
            if (description.TryGetProperty("base_color.shader", out textureProperty))
            {
                SetMaterialTextureProperty("_MainTex", material, textureProperty);
                Color baseColor = new Color(1.0f, 1.0f, 1.0f, 1.0f - floatProperty);
                material.SetColor("_Color", baseColor);
            }
            else if (description.TryGetProperty("base_color", out vectorProperty))
            {
                if (QualitySettings.activeColorSpace == ColorSpace.Gamma)
                {
                    vectorProperty.x = Mathf.LinearToGammaSpace(vectorProperty.x);
                    vectorProperty.y = Mathf.LinearToGammaSpace(vectorProperty.y);
                    vectorProperty.z = Mathf.LinearToGammaSpace(vectorProperty.z);
                }

                vectorProperty.w = 1.0f - floatProperty;
                material.SetColor("_Color", vectorProperty);
            }

            if (description.TryGetProperty("normal.shader", out textureProperty))
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);
                material.EnableKeyword("_NORMALMAP");
            }
            if (description.TryGetProperty("specular_roughness", out textureProperty))
            {
                SetMaterialTextureProperty("_SpecGlossMap", material, textureProperty);
                material.EnableKeyword("_SPECGLOSSMAP");
            }
            else if (description.TryGetProperty("specular_roughness", out floatProperty))
            {
                material.SetFloat("_Glossiness", floatProperty);
            }
            if (description.TryGetProperty("metalness", out textureProperty))
            {
                SetMaterialTextureProperty("_MetallicGlossMap", material, textureProperty);
                material.EnableKeyword("_METALLICGLOSSMAP");
            }

            if (description.TryGetProperty("emission", out floatProperty) && floatProperty > 0.0f)
            {
                Color emissiveColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
                if (description.TryGetProperty("emission_color.shader", out textureProperty))
                {
                    emissiveColor *= floatProperty;
                    SetMaterialTextureProperty("_EmissionMap", material, textureProperty);
                    material.SetColor("_EmissionColor", emissiveColor);
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
                else if (description.TryGetProperty("emission_color", out vectorProperty))
                {
                    emissiveColor = vectorProperty * floatProperty;
                    material.SetColor("_EmissionColor", emissiveColor);
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
            }
        }
        public PhysxPhysicObject(Scene scene, Geometry geometry, float mass, Matrix localTransformation, Matrix worldTransformation, Vector3 scale, MaterialDescription MaterialDescription)
        {
            Scale      = scale;
            rigidActor = scene.Physics.CreateRigidDynamic(worldTransformation.AsPhysX());
            material   = scene.Physics.CreateMaterial(MaterialDescription.StaticFriction, MaterialDescription.DynamicFriction, MaterialDescription.Bounciness);
            var boxShape = rigidActor.CreateShape(geometry, material, localTransformation.AsPhysX());

            rigidActor.SetMassAndUpdateInertia(mass);
        }