Пример #1
0
        private void UpdateGeometry(Shader shader)
        {
            Mesh mesh     = new Mesh();
            var  roomSize = 8;
            var  plane    = Meshes.CreateQuad(roomSize, roomSize, 2, 2);
            var  xform    = new Transformation();

            xform.TranslateGlobal(0, -roomSize / 2, 0);
            mesh.Add(plane.Transform(xform));
            xform.RotateZGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateZGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateZGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateYGlobal(90f);
            mesh.Add(plane.Transform(xform));
            xform.RotateYGlobal(180f);
            mesh.Add(plane.Transform(xform));

            var sphere = Meshes.CreateSphere(1);

            mesh.Add(sphere);
            var suzanne = Obj2Mesh.FromObj(Resourcen.suzanne);

            mesh.Add(suzanne.Transform(System.Numerics.Matrix4x4.CreateTranslation(2, 2, -2)));
            geometry = VAOLoader.FromMesh(mesh, shader);
        }
Пример #2
0
 public void ShaderChanged(string name, Shader shader)
 {
     if (ShaderName == name)
     {
         this.shader = shader;
         if (ReferenceEquals(shader, null))
         {
             return;
         }
         Mesh mesh   = Meshes.CreateQuad(10, 10, 10, 10);
         var  sphere = Meshes.CreateSphere(0.5f, 2);
         sphere.SetConstantUV(new System.Numerics.Vector2(0.5f, 0.5f));
         var xform = new Transformation();
         xform.TranslateLocal(0, 2, -2);
         mesh.Add(sphere.Transform(xform));
         xform.TranslateGlobal(0, 0, 2);
         mesh.Add(sphere.Transform(xform));
         xform.TranslateGlobal(2, 0, -1);
         mesh.Add(sphere.Transform(xform));
         geometry = VAOLoader.FromMesh(mesh, shader);
     }
     else if (ShaderDepthName == name)
     {
         this.shaderDepth = shader;
         if (ReferenceEquals(shaderDepth, null))
         {
             return;
         }
         //todo: radeon cards make errors with geometry bound to one shader and use in other shaders because of binding id changes
     }
 }
Пример #3
0
        public MainVisual(IRenderState renderState, IContentLoader contentLoader)
        {
            renderState.Set(new ClearColorState(1, 1, 1, 1));
            renderState.Set(new DepthTest(true));
            renderState.Set(new FaceCullingModeState(FaceCullingMode.BACK_SIDE));

            var envMap = contentLoader.Load <ITexture2D>("beach");

            envMap.WrapFunction = TextureWrapFunction.MirroredRepeat;
            envMap.Filter       = TextureFilterMode.Linear;
            var textureBinding = new TextureBinding[] { new TextureBinding(nameof(envMap), envMap) };

            var sphere = Meshes.CreateSphere(1f, 4);

            var skySphere        = sphere.Transform(Transformation.Scale(200f)).SwitchTriangleMeshWinding();
            var shaderBackground = contentLoader.Load <IShaderProgram>("background.*");

            visuals.Add(new MeshVisual(skySphere, shaderBackground, textureBinding));

#if SOLUTION
            var shaderEnvMap = contentLoader.Load <IShaderProgram>("envMapping.*");
            var visSphere    = new MeshVisual(sphere, shaderEnvMap, textureBinding);
            visSphere.SetUniform("reflective", 1f);
            visuals.Add(visSphere);
            var suzanne    = contentLoader.Load <DefaultMesh>("suzanne");
            var visSuzanne = new MeshVisual(suzanne.Transform(Transformation.Translation(0, -1.5f, 0)), shaderEnvMap, textureBinding);
            visSuzanne.SetUniform("reflective", 0.4f);
            visuals.Add(visSuzanne);
#endif
        }
Пример #4
0
        /// <summary>Promotes the specified object into a physical connector object.</summary>
        /// <remarks>
        /// The physics will immediately start on the object. If it doesn't have a rigidbody, the one will
        /// be created.
        /// </remarks>
        /// <param name="ownerModule">The part's module which will control the connector.</param>
        /// <param name="obj">The object to be promoted.</param>
        /// <param name = "interactionDistance"></param>
        public static KASInternalPhysicalConnector Promote(
            PartModule ownerModule, GameObject obj, float interactionDistance = 0)
        {
            var connectorRb = obj.GetComponent <Rigidbody>() ?? obj.AddComponent <Rigidbody>();

            connectorRb.useGravity      = false;
            connectorRb.isKinematic     = ownerModule.part.packed;
            connectorRb.velocity        = ownerModule.part.rb.velocity;
            connectorRb.angularVelocity = ownerModule.part.rb.angularVelocity;
            connectorRb.ResetInertiaTensor();
            connectorRb.ResetCenterOfMass();
            var connectorModule = obj.AddComponent <KASInternalPhysicalConnector>();

            connectorModule.ownerModule = ownerModule;

            // Create the interaction collider if requested.
            if (interactionDistance > 0)
            {
                // This mesh is placed on a special layer which is not rendered in the game. It's only
                // used to detect the special zones triggers (like ladders, hatches, etc.).
                var interactionTriggerObj = Meshes.CreateSphere(
                    2 * interactionDistance, null, obj.transform, Colliders.PrimitiveCollider.Shape);
                interactionTriggerObj.name  = InteractionAreaCollider;
                interactionTriggerObj.layer = (int)KspLayer.TriggerCollider;
                interactionTriggerObj.gameObject.GetComponent <Collider>().isTrigger = true;
                connectorModule.interactionTriggerObj = interactionTriggerObj;
            }

            return(connectorModule);
        }
Пример #5
0
        public MainVisual(IRenderState renderState, IContentLoader contentLoader)
        {
            renderState.Set(new DepthTest(true));
            renderState.Set(new FaceCullingModeState(FaceCullingMode.BACK_SIDE));

            shaderProgramPhong = contentLoader.Load <IShaderProgram>("phong.*");
            var mesh     = new DefaultMesh();
            var roomSize = 8;
            //off-center plane
            var plane = Meshes.CreatePlane(roomSize, roomSize, 2, 2).Transform(Transformation.Translation(0, -roomSize / 2, 0));

            mesh.Add(plane);
            //rotate plane to create box
            mesh.Add(plane.Transform(Transformation.Rotation(90f, Axis.Z)));
            mesh.Add(plane.Transform(Transformation.Rotation(180f, Axis.Z)));
            mesh.Add(plane.Transform(Transformation.Rotation(270f, Axis.Z)));
            mesh.Add(plane.Transform(Transformation.Rotation(90f, Axis.X)));
            mesh.Add(plane.Transform(Transformation.Rotation(-90f, Axis.X)));

            var sphere = Meshes.CreateSphere(1);

            sphere.SetConstantUV(Vector2.Zero);             //all other meshes have texture coordinates
            mesh.Add(sphere);
            var suzanne = contentLoader.Load <DefaultMesh>("suzanne");

            mesh.Add(suzanne.Transform(Transformation.Translation(2, 2, -2)));
            geometryPhong = VAOLoader.FromMesh(mesh, shaderProgramPhong);

            shaderProgramToon = contentLoader.Load <IShaderProgram>("toon.*");
            geometryToon      = VAOLoader.FromMesh(suzanne.Transform(Transformation.Translation(2, 0, 0)), shaderProgramToon);
        }
Пример #6
0
        public MainVisual(IRenderState renderState, IContentLoader contentLoader)
        {
            renderState.Set(BoolState <IDepthState> .Enabled);
            renderState.Set(BoolState <IBackfaceCullingState> .Enabled);
            renderState.Set(BlendStates.AlphaBlend);

            shaderProgram = contentLoader.Load <IShaderProgram>("phong.*");
            var mesh     = new DefaultMesh();
            var roomSize = 8;
            //off-center plane
            var plane = Meshes.CreatePlane(roomSize, roomSize, 2, 2).Transform(new Translation3D(0, -roomSize / 2, 0));

            mesh.Add(plane);
            //rotate plane to create box
            mesh.Add(plane.Transform(new Rotation3D(Axis.Z, 90f)));
            mesh.Add(plane.Transform(new Rotation3D(Axis.Z, 180f)));
            mesh.Add(plane.Transform(new Rotation3D(Axis.Z, 270f)));
            mesh.Add(plane.Transform(new Rotation3D(Axis.X, 90f)));
            mesh.Add(plane.Transform(new Rotation3D(Axis.X, -90f)));

            var sphere = Meshes.CreateSphere(1);

            sphere.SetConstantUV(new Vector2(0, 0));
            mesh.Add(sphere);
            var suzanne = contentLoader.Load <DefaultMesh>("suzanne");

            mesh.Add(suzanne.Transform(new Translation3D(2, 2, -2)));
            geometry = VAOLoader.FromMesh(mesh, shaderProgram);
        }
Пример #7
0
        public DeferredRenderer(IContentLoader contentLoader, IRenderState renderState)
        {
            renderState.Set <DepthTest>(new DepthTest(true));
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.Blend);
            GL.CullFace(CullFaceMode.Back);


            this.renderState   = renderState;
            this.contentLoader = contentLoader;

            deferredParticleShader        = contentLoader.Load <IShaderProgram>("deferred_particle.*");
            shadowMapShaderParticle       = contentLoader.Load <IShaderProgram>("shadowMapParticle.*");
            shadowLightViewShaderParticle = contentLoader.Load <IShaderProgram>("shadowLightViewParticle.*");

            deferredGeometryShader = contentLoader.Load <IShaderProgram>("deferred_geometry.*");

            deferredPost          = contentLoader.LoadPixelShader("deferred_post");
            pointLightShader      = contentLoader.Load <IShaderProgram>("def_pointLight.*");
            shadowMapShader       = contentLoader.Load <IShaderProgram>("shadowMap.*");
            shadowLightViewShader = contentLoader.Load <IShaderProgram>("shadowLightView.*");
            var lmesh = Meshes.CreateSphere(1, 2);

            pointLightSphere = VAOLoader.FromMesh(lmesh, pointLightShader);
        }
Пример #8
0
        public SphereCut(IContentLoader contentLoader, float size)
        {
            _sphereCutProgram = contentLoader.Load <IShaderProgram>("imageOnGeometry.*");

            var sphere = Meshes.CreateSphere(size, 5).SwitchHandedness();

            _sphereGeometry = VAOLoader.FromMesh(sphere, _sphereCutProgram);
        }
Пример #9
0
        private static VAO CreateMesh(Shader shader)
        {
            Mesh mesh = Meshes.CreateSphere(0.03f, 2);
            var  vao  = new VAO();

            vao.SetAttribute(shader.GetAttributeLocation("position"), mesh.positions.ToArray(), VertexAttribPointerType.Float, 3);
            vao.SetAttribute(shader.GetAttributeLocation("normal"), mesh.normals.ToArray(), VertexAttribPointerType.Float, 3);
            vao.SetID(mesh.ids.ToArray(), PrimitiveType.Triangles);
            return(vao);
        }
Пример #10
0
        private void UpdateGeometry(Shader shader)
        {
            var mesh   = new Mesh();
            var sphere = Meshes.CreateSphere(1, 4);

            mesh.Add(sphere);
            var suzanne = Obj2Mesh.FromObj(Resourcen.suzanne);

            mesh.Add(suzanne.Transform(System.Numerics.Matrix4x4.CreateTranslation(2, 2, -2)));
            geometry = VAOLoader.FromMesh(mesh, shader);
        }
Пример #11
0
        public MainVisual(IRenderState renderState, IContentLoader contentLoader)
        {
            renderState.Set(new DepthTest(true));
            renderState.Set(new FaceCullingModeState(FaceCullingMode.BACK_SIDE));

            shaderProgram = contentLoader.Load <IShaderProgram>("shader.*");
            var mesh = Meshes.CreateSphere(0.03f, 2);

#if SOLUTION
            mesh = contentLoader.Load <DefaultMesh>("suzanne").Transform(Transformation.Scale(0.03f));
#endif
            geometry = VAOLoader.FromMesh(mesh, shaderProgram);

            InitParticles();
        }
Пример #12
0
        public void ShaderChanged(string name, Shader shader)
        {
            if (ShaderName != name)
            {
                return;
            }
            if (ReferenceEquals(shader, null))
            {
                return;
            }
            var sphere    = Meshes.CreateSphere(1, 4);
            var envSphere = sphere.SwitchTriangleMeshWinding();

            envSphere.Add(sphere);
            geometry = VAOLoader.FromMesh(envSphere, shader);
        }
Пример #13
0
        public MainVisual(IRenderState renderState, IContentLoader contentLoader)
        {
            renderState.Set(new DepthTest(true));
            fboShadowMap.Texture.Filter = TextureFilterMode.Nearest;

            shaderProgram = contentLoader.Load <IShaderProgram>("shadowMap.*");
            var mesh   = Meshes.CreatePlane(10, 10, 10, 10);
            var sphere = Meshes.CreateSphere(0.5f, 2);

            sphere.SetConstantUV(new Vector2(0.5f, 0.5f));
            mesh.Add(sphere.Transform(Transformation.Translation(0, 2, -2)));
            mesh.Add(sphere.Transform(Transformation.Translation(0, 2, 0)));
            mesh.Add(sphere.Transform(Transformation.Translation(2, 2, -1)));
            geometry = VAOLoader.FromMesh(mesh, shaderProgram);

            shaderProgramDepth = contentLoader.Load <IShaderProgram>("depth.*");
            //todo: radeon cards created errors with geometry bound to one shader and used in other shaders because of binding id changes
        }
Пример #14
0
        public Skybox(IContentLoader contentLoader, float size, string textureName)
        {
            _skyboxProgram = contentLoader.Load <IShaderProgram>("sky.*");

            ITexture2D[] textures = new ITexture2D[6];

            for (int i = 0; i < 6; i++)
            {
                textures[i] = contentLoader.Load <ITexture2D>(textureName + Endings[i]);
            }

            _cubeFbo = new CubeMapFBO(textures[0].Width);

            CreateMap(textures);

            var sphere = Meshes.CreateSphere(size).SwitchHandedness();

            _sphereGeometry = VAOLoader.FromMesh(sphere, _skyboxProgram);
        }
Пример #15
0
        private void UpdateGeometry(Shader shader)
        {
            Mesh mesh = Meshes.CreateSphere(0.03f, 2);

            geometry = VAOLoader.FromMesh(mesh, shader);

            //per instance attributes
            var          rnd               = new Random(12);
            Func <float> Rnd01             = () => (float)rnd.NextDouble();
            Func <float> RndCoord          = () => (Rnd01() - 0.5f) * 2.0f;
            var          instancePositions = new Vector3[instanceCount];

            for (int i = 0; i < instanceCount; ++i)
            {
                instancePositions[i] = new Vector3(RndCoord(), RndCoord(), RndCoord());
            }
            geometry.SetAttribute(shader.GetAttributeLocation("instancePosition"), instancePositions, VertexAttribPointerType.Float, 3, true);

            //todo students: add per instance attribute speed here
        }
Пример #16
0
        public MainVisual(IRenderState renderState, IContentLoader contentLoader)
        {
            this.renderState = renderState;
            var shaderMaterial = contentLoader.Load <IShaderProgram>("material.*");

            var plane = Meshes.CreatePlane(4, 4, 1, 1);

            meshVisuals.Add(new MeshVisual(plane, shaderMaterial));
            var instanceMesh     = contentLoader.Load <DefaultMesh>("suzanne").Transform(Transformation.Scale(0.03f));
            var instanceData     = CreateInstancePositionMaterial(20, 20);
            var suzanneInstances = VAOLoader.FromMesh(instanceMesh, shaderMaterial);

            suzanneInstances.SetAttribute(shaderMaterial.GetResourceLocation(ShaderResourceType.Attribute, nameof(instanceData)), instanceData, true);
            meshVisuals.Add(new MeshVisual(suzanneInstances, shaderMaterial));
            var shaderLighting = contentLoader.Load <IShaderProgram>("lighting.*");
            var lightMesh      = Meshes.CreateSphere(1f, 2);        // either make it bigger or you need good subdivision to avoid border artifacts
            var lightGeometry  = VAOLoader.FromMesh(lightMesh, shaderLighting);

            lightGeometry.SetAttribute(shaderLighting.GetResourceLocation(ShaderResourceType.Attribute, "lightData"), instanceData, true);
            lightsVisual = new MeshVisual(lightGeometry, shaderLighting);
        }
Пример #17
0
        public MainVisual(IRenderState renderState, IContentLoader contentLoader)
        {
            renderState.Set(new ClearColorState(1, 1, 1, 1));
            renderState.Set(BoolState <IDepthState> .Enabled);
            renderState.Set(BoolState <IBackfaceCullingState> .Enabled);

            envMap = contentLoader.Load <ITexture2D>("beach");
            envMap.WrapFunction = TextureWrapFunction.MirroredRepeat;
            envMap.Filter       = TextureFilterMode.Linear;

            sphereTex = contentLoader.Load <ITexture2D>("hatefield1");
            sphereTex.WrapFunction = TextureWrapFunction.MirroredRepeat;
            sphereTex.Filter       = TextureFilterMode.Linear;

            shaderProgram = contentLoader.Load <IShaderProgram>("envMapping.*");

            var sphere        = Meshes.CreateSphere(1, 4);
            var envSphere     = sphere.SwitchTriangleMeshWinding();
            var refSphere     = Meshes.CreateSphere(.1f, 4).Transform(new Translation3D(new Vector3(-.1f, 0, 0)));
            var refractSphere = Meshes.CreateSphere(.1f, 4).Transform(new Translation3D(new Vector3(.1f, 0, 0)));

            geometry = VAOLoader.FromMesh(envSphere, shaderProgram);
            geometry.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "specularity"), new[] { 0.0f }, VertexAttribPointerType.Float, 1, true);
            geometry.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "translucency"), new[] { 0.0f }, VertexAttribPointerType.Float, 1, true);
            geometry.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "refractionIndex"), new[] { 1.0f }, VertexAttribPointerType.Float, 1, true);

            geometryRef = VAOLoader.FromMesh(refSphere, shaderProgram);
            geometryRef.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "specularity"), new[] { .2f }, VertexAttribPointerType.Float, 1, true);
            geometryRef.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "translucency"), new[] { 0.0f }, VertexAttribPointerType.Float, 1, true);
            geometryRef.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "refractionIndex"), new[] { 1.0f }, VertexAttribPointerType.Float, 1, true);

            geometryRefract = VAOLoader.FromMesh(refractSphere, shaderProgram);
            geometryRefract.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "specularity"), new[] { .0f }, VertexAttribPointerType.Float, 1, true);
            geometryRefract.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "translucency"), new[] { 1.0f }, VertexAttribPointerType.Float, 1, true);
            geometryRefract.SetAttribute(shaderProgram.GetResourceLocation(ShaderResourceType.Attribute, "refractionIndex"), new[] { 1.6f }, VertexAttribPointerType.Float, 1, true);
        }
Пример #18
0
        public void ShaderChanged(string name, Shader shader)
        {
            if (ShaderName == name)
            {
                this.shaderObject = shader;
                if (ReferenceEquals(shader, null))
                {
                    return;
                }

                // cloud
                // cloud needs to be translated higher to "get" the (beginning) light from below
                Mesh cloudMesh = Obj2Mesh.FromObj(Resourcen.cloud);
                this.cloud = VAOLoader.FromMesh(cloudMesh, shader);
                // table
                Mesh tableClothMesh = Obj2Mesh.FromObj(Resourcen.tableCloth);
                this.tableCloth = VAOLoader.FromMesh(tableClothMesh, shader);
                // table top
                Mesh tableMesh = Obj2Mesh.FromObj(Resourcen.table);
                this.table = VAOLoader.FromMesh(tableMesh, shader);
                // candle
                Mesh candleMesh = Obj2Mesh.FromObj(Resourcen.candle);
                this.candle = VAOLoader.FromMesh(candleMesh, shader);
                // plate
                Mesh plateMesh = Obj2Mesh.FromObj(Resourcen.plate);
                this.plate = VAOLoader.FromMesh(plateMesh, shader);
                // grape plate
                var xform = new Transformation();
                xform.ScaleGlobal(new System.Numerics.Vector3(.8f));
                Mesh grapePlateMesh = Obj2Mesh.FromObj(Resourcen.plate);
                this.grapePlate = VAOLoader.FromMesh(grapePlateMesh.Transform(xform), shader);
                // wine bottle
                Mesh wineBottleMesh = Obj2Mesh.FromObj(Resourcen.wineBottle);
                this.wineBottle = VAOLoader.FromMesh(wineBottleMesh, shader);
                // wine bottle label
                Mesh wineBottleLabelMesh = Obj2Mesh.FromObj(Resourcen.wineBottleLabel);
                this.wineBottleLabel = VAOLoader.FromMesh(wineBottleLabelMesh, shader);
                // wine bottle shutter
                Mesh wineBottleShutterMesh = Obj2Mesh.FromObj(Resourcen.wineBottleShutter);
                this.wineBottleShutter = VAOLoader.FromMesh(wineBottleShutterMesh, shader);
                // grapes
                Mesh grapesMesh = Obj2Mesh.FromObj(Resourcen.grapes);
                this.grapes = VAOLoader.FromMesh(grapesMesh, shader);
                // knife left
                Mesh knifeLeftMesh = Obj2Mesh.FromObj(Resourcen.knife);
                this.knifeLeft = VAOLoader.FromMesh(knifeLeftMesh, shader);
                // knife right
                var xform_ = new Transformation();
                xform_.RotateYGlobal(180f);
                Mesh knifeRightMesh = Obj2Mesh.FromObj(Resourcen.knife);
                this.knifeRight = VAOLoader.FromMesh(knifeRightMesh.Transform(xform_), shader);
                // fork left
                Mesh forkLeftMesh = Obj2Mesh.FromObj(Resourcen.fork);
                this.forkLeft = VAOLoader.FromMesh(forkLeftMesh, shader);
                // fork right
                Mesh forkRightMesh = Obj2Mesh.FromObj(Resourcen.fork);
                this.forkRight = VAOLoader.FromMesh(forkRightMesh.Transform(xform_), shader);
                // environment sphere
                var sphere    = Meshes.CreateSphere(6, 4);
                var envSphere = sphere.SwitchTriangleMeshWinding();
                this.environment = VAOLoader.FromMesh(envSphere, shader);
            }
            else if (ShaderShadowName == name)
            {
                this.shaderShadow = shader;
                if (ReferenceEquals(shaderObject, null))
                {
                    return;
                }
            }
        }
Пример #19
0
        /// <summary>Builds a model for the joint end basing on the procedural configuration.</summary>
        /// <param name="modelName">Joint transform name.</param>
        /// <param name="config">Joint configuration from the part's config.</param>
        protected virtual void CreateJointEndModels(string modelName, JointConfig config)
        {
            // FIXME: Prefix the model name with the renderer name.
            // Make or get the root.
            Transform root = null;

            if (config.type == PipeEndType.PrefabModel)
            {
                root = Hierarchy.FindTransformByPath(partModelTransform, config.modelPath);
                if (root != null)
                {
                    root.parent = partModelTransform; // We need the part's model to be the root.
                    var partAttach = new GameObject(PartJointTransformName).transform;
                    Hierarchy.MoveToParent(partAttach, root,
                                           newPosition: config.partAttachAt.pos,
                                           newRotation: config.partAttachAt.rot);
                    var pipeAttach = new GameObject(PipeJointTransformName);
                    Hierarchy.MoveToParent(pipeAttach.transform, root,
                                           newPosition: config.pipeAttachAt.pos,
                                           newRotation: config.pipeAttachAt.rot);
                }
                else
                {
                    HostedDebugLog.Error(this, "Cannot find model: {0}", config.modelPath);
                    config.type = PipeEndType.Simple; // Fallback.
                }
            }
            if (root == null)
            {
                root = new GameObject().transform;
                Hierarchy.MoveToParent(root, partModelTransform);
                var partJoint = new GameObject(PartJointTransformName).transform;
                Hierarchy.MoveToParent(partJoint, root);
                partJoint.rotation = Quaternion.LookRotation(Vector3.forward);
                if (config.type == PipeEndType.ProceduralModel)
                {
                    // Create procedural models at the point where the pipe connects to the part's node.
                    var material = CreateMaterial(
                        GetTexture(config.texture),
                        mainTexNrm: config.textureNrm != "" ? GetTexture(config.textureNrm) : null);
                    var sphere = Meshes.CreateSphere(config.sphereDiameter, material, root,
                                                     colliderType: Colliders.PrimitiveCollider.Shape);
                    sphere.name = PipeJointTransformName;
                    sphere.transform.rotation = Quaternion.LookRotation(Vector3.back);
                    RescaleTextureToLength(sphere, samplesPerMeter: config.textureSamplesPerMeter);
                    if (Mathf.Abs(config.sphereOffset) > float.Epsilon)
                    {
                        sphere.transform.localPosition += new Vector3(0, 0, config.sphereOffset);
                        if (config.armDiameter > float.Epsilon)
                        {
                            var arm = Meshes.CreateCylinder(
                                config.armDiameter, config.sphereOffset, material, root,
                                colliderType: Colliders.PrimitiveCollider.Shape);
                            arm.transform.localPosition += new Vector3(0, 0, config.sphereOffset / 2);
                            arm.transform.LookAt(sphere.transform.position);
                            RescaleTextureToLength(arm, samplesPerMeter: config.textureSamplesPerMeter);
                        }
                    }
                }
                else
                {
                    // No extra models are displayed at the joint, just attach the pipe to the part's node.
                    if (config.type != PipeEndType.Simple)
                    {
                        // Normally, this error should never pop up.
                        HostedDebugLog.Error(this, "Unknown joint type: {0}", config.type);
                    }
                    var pipeJoint = new GameObject(PipeJointTransformName);
                    Hierarchy.MoveToParent(pipeJoint.transform, root);
                    pipeJoint.transform.rotation = Quaternion.LookRotation(Vector3.back);
                }
            }
            Colliders.UpdateColliders(root.gameObject, isPhysical: config.colliderIsPhysical);
            root.gameObject.SetActive(false);
            root.name = modelName;
        }
Пример #20
0
        /// <summary>Builds a model for the joint end basing on the configuration.</summary>
        /// <param name="node">The node to setup.</param>
        /// <param name="alignTo">
        /// The object to align the conenctor to. If it's <c>null</c>, then the model will be parked.
        /// </param>
        protected virtual void UpdateJointNode(ModelPipeEndNode node, Transform alignTo)
        {
            var config = node.config;
            var makeProceduralModels = alignTo != null || !config.parkPrefabOnly;

            // Return the models back to the owner part to make the search working properly.
            if (node.rootModel != null)
            {
                node.AlignToTransform(null);
            }

            node.parkRootObject = partModelTransform;

            // Create basic setup.
            var nodeName = ModelBasename + "-pipeNode" + node.name;

            node.rootModel = partModelTransform.Find(nodeName)
                             ?? new GameObject(nodeName).transform;
            node.rootModel.parent = partModelTransform;
            node.partAttach       = node.rootModel.Find(PartJointTransformName)
                                    ?? new GameObject(PartJointTransformName).transform;
            Hierarchy.MoveToParent(node.partAttach, node.rootModel,
                                   newPosition: Vector3.zero,
                                   newRotation: Quaternion.LookRotation(Vector3.back));
            node.pipeAttach = node.rootModel.Find(PipeJointTransformName)
                              ?? new GameObject(PipeJointTransformName).transform;
            Hierarchy.MoveToParent(node.pipeAttach, node.rootModel,
                                   newPosition: Vector3.zero,
                                   newRotation: Quaternion.LookRotation(Vector3.forward));

            // Add a pipe attachment sphere if set.
            const string sphereName = "pipeSphere";
            var          sphere     = node.pipeAttach.Find(sphereName);

            if (config.sphereDiameter > float.Epsilon && makeProceduralModels)
            {
                if (sphere == null)
                {
                    sphere = Meshes.CreateSphere(config.sphereDiameter, pipeMaterial, node.pipeAttach,
                                                 colliderType: Colliders.PrimitiveCollider.Shape).transform;
                    sphere.name     = sphereName;
                    sphere.rotation = Quaternion.LookRotation(node.partAttach.up, node.partAttach.forward);
                }
                sphere.GetComponent <Renderer>().sharedMaterial = pipeMaterial; // For performance.
                RescalePipeTexture(sphere, sphere.localScale.z * config.sphereDiameter * 2.0f);
            }
            else if (sphere != null)
            {
                Hierarchy.SafeDestory(sphere);
            }

            // Parking position, if defined.
            var parkObjectName = ModelBasename + "-park" + node.name;
            var parkAttach     = partModelTransform.Find(parkObjectName);

            if (config.parkAttachAt != null)
            {
                node.parkAttach = parkAttach ?? new GameObject(parkObjectName).transform;
                Hierarchy.MoveToParent(node.parkAttach, partModelTransform,
                                       newPosition: config.parkAttachAt.pos,
                                       newRotation: config.parkAttachAt.rot);
            }
            else if (parkAttach != null)
            {
                Hierarchy.SafeDestory(parkAttach);
            }

            // Place prefab between the part and the pipe if specified.
            if (!string.IsNullOrEmpty(config.modelPath))
            {
                // The prefab model can move to the part's model, so make a unique name for it.
                const string prefabName  = "prefabConnector";
                var          prefabModel = node.rootModel.Find(prefabName)
                                           ?? Hierarchy.FindTransformByPath(partModelTransform, config.modelPath);
                if (prefabModel != null)
                {
                    prefabModel.gameObject.SetActive(true);
                    prefabModel.name         = prefabName;
                    prefabModel.parent       = node.rootModel;
                    prefabModel.rotation     = node.partAttach.rotation * config.modelPartAttachAt.rot.Inverse();
                    prefabModel.position     = node.partAttach.TransformPoint(config.modelPartAttachAt.pos);
                    node.pipeAttach.rotation = prefabModel.rotation * config.modelPipeAttachAt.rot;
                    node.pipeAttach.position = prefabModel.TransformPoint(config.modelPipeAttachAt.pos);
                }
                else
                {
                    HostedDebugLog.Error(this, "Cannot find prefab model: {0}", config.modelPath);
                }
            }

            // The offset is intended for the sphere/arm models only.
            if (makeProceduralModels)
            {
                node.pipeAttach.localPosition += new Vector3(0, 0, config.sphereOffset);
            }

            // Add arm pipe.
            const string armName = "sphereArm";
            var          arm     = node.pipeAttach.Find(armName);

            if (config.armDiameter > float.Epsilon && config.sphereOffset > float.Epsilon &&
                makeProceduralModels)
            {
                if (arm == null)
                {
                    arm = Meshes.CreateCylinder(config.armDiameter, config.sphereOffset, pipeMaterial,
                                                node.pipeAttach,
                                                colliderType: Colliders.PrimitiveCollider.Shape).transform;
                    arm.name = armName;
                }
                arm.GetComponent <Renderer>().sharedMaterial = pipeMaterial; // For performance.
                arm.transform.localPosition = new Vector3(0, 0, -config.sphereOffset / 2);
                arm.transform.localRotation = Quaternion.LookRotation(Vector3.forward);
                RescalePipeTexture(arm.transform, arm.localScale.z * config.sphereOffset);
            }
            else if (arm != null)
            {
                Hierarchy.SafeDestory(arm);
            }

            // Adjust to the new target.
            node.AlignToTransform(alignTo);
        }
Пример #21
0
        private List <Entity> GetGeometry(DeferredRenderer renderer)
        {
            IShaderProgram defaultShader = renderer.GetShader(DeferredRenderer.DrawableType.deferredDefaultMesh);
            List <Entity>  res           = new List <Entity>();
            float          islandScale   = 30f;
            var            islePlane     = Meshes.CreatePlane(30, 30, 120, 120).Transform(Transformation.Translation(0, islandScale / 2, 0));
            Renderable     isle          = ContentFactory.GetDefaultRenderable(renderer, islePlane);


            ITexture2D isleAlbedo = contentLoader.Load <ITexture2D>("terrain.png");

            isleAlbedo.Filter = TextureFilterMode.Linear;
            //ITexture2D isleNormal = contentLoader.Load<ITexture2D>("normalTest1.jpg");
            isle.SetAlbedoTexture(isleAlbedo);
            //isle.SetNormalMap(isleNormal);
            ITexture2D isleHeightmap = contentLoader.Load <ITexture2D>("hmapUnity.png");

            isle.SetHeightMap(isleHeightmap);
            isle.heightScaleFactor = islandScale;
            Entity isleEntity = new Entity();

            isleEntity.name       = "isle";
            isleEntity.renderable = isle;

            Terrain isleTerrain = new Terrain(contentLoader, "hmapUnity.png", islandScale, 30, 30);

            isleTerrain.transform.position = new Vector3(0, islandScale / 2, 0);



            var        waterplane       = Meshes.CreatePlane(100, 100, 225, 225).Transform(Transformation.Translation(0, 1f, 0));
            VAO        waterDrawable    = renderer.GetDrawable(waterplane, DeferredRenderer.DrawableType.deferredDefaultMesh);
            Renderable water            = ContentFactory.GetDefaultRenderable(renderer, waterplane);
            ITexture2D waterEnvironment = contentLoader.Load <ITexture2D>("sky_low.jpg");

            water.SetEnvironmentMap(waterEnvironment);
            water.reflectivity = 1;
            //water.SetAlbedoTexture(isleAlbedo);
            Entity waterEntity = new Entity();

            waterEntity.name       = "water";
            waterEntity.renderable = water;

            var        grassPlane = Meshes.CreatePlane(1, 1, 2, 2).Transform(Transformation.Rotation(-90, Axis.X));
            Renderable grass      = ContentFactory.GetDefaultRenderable(renderer, grassPlane);

            grass.faceCullingMode = FaceCullingMode.NONE;
            ITexture2D grassAlbedo = contentLoader.Load <ITexture2D>("Grass_512_albedo.tif");
            ITexture2D grassAlpha  = contentLoader.Load <ITexture2D>("tGrass_512_alpha.tif");

            grass.SetAlbedoTexture(grassAlbedo);
            grass.SetAlphaMap(grassAlpha);
            //Entity grassEntity = new Entity();
            //grassEntity.renderable = grass;
            Vector3[]    spawnPositions = { new Vector3(-0.1f, 7.1f, 2.5f), new Vector3(-3.5f, 7.1f, -1.5f),
                                            new Vector3(6f,       7.1f, 2.5f), new Vector3(6f,    7.1f, -1.5f),new Vector3(5f,7.1f, -6f), new Vector3(1f, 7.1f, -8f), new Vector3(-3f, 7.1f, -8f) };
            float[]      radius      = { 2f, 1.9f, 2f, 2f, 2f, 2f, 2f };
            int[]        amountGrass = { 50, 60, 50, 60, 60, 60, 60 };
            Range3D      scaleRange  = new Range3D(new Vector3(0.5f), new Vector3(1.5f));
            TerrainLayer layer       = new TerrainLayer(isleTerrain, grass);

            for (int i = 0; i < spawnPositions.Length; i++)
            {
                SphericalTerrainSpawner grassSpawner = new SphericalTerrainSpawner(spawnPositions[i], radius[i], amountGrass[i]);
                grassSpawner.randomScaleRange = scaleRange;
                layer.AddSpawner(grassSpawner);
            }
            layer.SpawnElements();
            res.Add(layer);
            var skysphere = Meshes.CreateSphere(60, 2);

            skysphere.SwitchTriangleMeshWinding();
            Renderable skydome = ContentFactory.GetDefaultRenderable(renderer, skysphere);

            skydome.faceCullingMode = FaceCullingMode.FRONT_SIDE;
            skydome.unlit           = 1;
            skydome.SetAlbedoTexture(waterEnvironment);
            Entity skyEntity = new Entity();

            skyEntity.renderable = skydome;
            skyEntity.name       = "skydome";

            var        msphere = Meshes.CreateSphere(1, 2).Transform(Transformation.Translation(0, 2, 0));
            Renderable sphere  = ContentFactory.GetDefaultRenderable(renderer, msphere);
            VAO        spVao   = renderer.GetDrawable(msphere, DeferredRenderer.DrawableType.deferredDefaultMesh);

            sphere.SetEnvironmentMap(waterEnvironment);
            Entity spEntity = new Entity();

            spEntity.name       = "sphere";
            spEntity.renderable = sphere;

            //res.Add(grassEntity);
            res.Add(isleEntity);
            res.Add(waterEntity);
            //res.Add(spEntity);
            res.Add(skyEntity);
            return(res);
        }