Exemple #1
0
        public void EnableRendering(Vector3 origin)
        {
            Vector3[] lineColors;
            int[]     lineIndicies;

            bboxShader = ShaderCompiler.BuildDefaultShader();
            bboxShader.Link();

            lineColors   = null;
            lineIndicies = null;

            lines(LineColor, 12, out lineColors, out lineIndicies);

            _geo                 = new Box.BoxGeometry();
            _pack                = new PackedGeometry();
            _pack.Coloring       = true;
            _pack._indices       = _geo.Indices;
            _pack._coords        = _geo.Vertices;
            _pack.color          = X3DTypeConverters.Vec3ToFloatArray(lineColors);
            _pack._colorIndicies = lineIndicies;
            _pack.restartIndex   = -1;
            _pack.Interleave();
            _handle = _pack.CreateHandle();

            renderingEnabled = _handle.HasGeometry;

            InitBoundaryPoints(origin);
        }
        public void TestContentDataURIs()
        {
            string dataUri;

            string[] uris;
            object   resource;
            bool     success;

            dataUri = "'data:text/plain\n#version 420 core 
\nlayout(location = 0) in vec3 position; 
'";


            uris = X3DTypeConverters.GetMFString(dataUri);
            Assert.IsTrue(uris.Length == 1);
            success = SceneManager.FetchSingle(uris[0], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            StreamReader reader                   = new StreamReader(resource as Stream);
            string       dataTextPlain            = reader.ReadToEnd();
            string       someTestShaderCodeSample = "#version 420 core 
\nlayout(location = 0) in vec3 position; 
";

            Assert.AreEqual(dataTextPlain, someTestShaderCodeSample);


            //TODO: complete tests for data:uri as seen in https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs
        }
        public void TestAbsoluteWebURIs()
        {
            string url;

            string[] uris;
            object   resource;
            bool     success;

            url = "\"http://www.web3d.org/x3d/content/examples/Basic/DistributedInteractiveSimulation/images/left.png\" \"http://www.web3d.org/x3d/content/examples/Basic/DistributedInteractiveSimulation/images/right.png\" \"http://www.web3d.org/x3d/content/examples/Basic/DistributedInteractiveSimulation/images/front.png\"";

            uris = X3DTypeConverters.GetMFString(url);

            Assert.IsTrue(uris.Length == 3);

            success = SceneManager.FetchSingle(uris[0], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);

            success = SceneManager.FetchSingle(uris[1], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);

            success = SceneManager.FetchSingle(uris[2], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
        }
        public override void Load()
        {
            base.Load();

            string navType = this.type.ToUpper();

            if (navType.Contains("ANY"))
            {
                NavigationType = NavigationType.Examine;
            }
            else if (navType.Contains("EXAMINE"))
            {
                NavigationType = NavigationType.Examine;
            }
            else if (navType.Contains("WALK"))
            {
                NavigationType = NavigationType.Walk;
            }
            else if (navType.Contains("FLY"))
            {
                NavigationType = NavigationType.Fly;
            }

            AvatarSize = X3DTypeConverters.SFVec3f(avatarSize);

            HeadlightEnabled = this.headlight;
        }
        public static PointSet CreateFromVertexSet(List <Vertex> verticies)
        {
            PointSet   ps;
            Coordinate coord;
            Color      colors;

            Vector3[] points;

            ps     = new PointSet();
            coord  = new Coordinate();
            colors = new Color();

            points       = verticies.Select(v => v.Position).ToArray();
            colors.color = X3DTypeConverters.ToString(verticies.Select(v => v.Color.Xyz).ToArray());
            coord.point  = X3DTypeConverters.ToString(points);

            coord.Parent  = ps;
            colors.Parent = ps;
            ps.Children.Add(colors);
            ps.Children.Add(coord);

            ps.PrimativeType = PrimitiveType.Points;

            return(ps);
        }
        public void TestMixedURIs()
        {
            string url;

            string[] uris;

            url = "\"c.jpg\" 'a.jpg' 'b.jpg' \"d.jpg\" 'e.jpg' \"f.jpg\" 'test-helloworld' "
                  + "\"subfolder0\\file0.png\\\" "
                  + "\"Figure14.2ElevationGridMountain.x3d\" "
                  + "'http://www.web3d.org/x3d/content/examples/Vrml2.0Sourcebook/Chapter14-ElevationGrid/Figure14.2ElevationGridMountain.x3d' "
                  + "\"http://www.web3d.org/x3d/content/examples/Vrml2.0Sourcebook/Chapter14-ElevationGrid/Figure14.2ElevationGridMountain.x3d\" "
                  + "'subfolder1\\subfolder1-subfolder\\file1.ext'";

            uris = X3DTypeConverters.GetMFString(url);

            Assert.IsTrue(uris.Length == 12);

            Assert.AreEqual(uris[0], "c.jpg");
            Assert.AreEqual(uris[1], "a.jpg");
            Assert.AreEqual(uris[2], "b.jpg");
            Assert.AreEqual(uris[3], "d.jpg");
            Assert.AreEqual(uris[4], "e.jpg");
            Assert.AreEqual(uris[5], "f.jpg");
            Assert.AreEqual(uris[6], "test-helloworld");
            Assert.AreEqual(uris[7], "subfolder0\\file0.png\\");
            Assert.AreEqual(uris[8], "Figure14.2ElevationGridMountain.x3d");
            Assert.AreEqual(uris[9], "http://www.web3d.org/x3d/content/examples/Vrml2.0Sourcebook/Chapter14-ElevationGrid/Figure14.2ElevationGridMountain.x3d");
            Assert.AreEqual(uris[10], "http://www.web3d.org/x3d/content/examples/Vrml2.0Sourcebook/Chapter14-ElevationGrid/Figure14.2ElevationGridMountain.x3d");
            Assert.AreEqual(uris[11], "subfolder1\\subfolder1-subfolder\\file1.ext");
        }
        public static PackedGeometry Pack(IndexedLineSet ils)
        {
            PackedGeometry packed;
            Coordinate     coordinate;

            packed = new PackedGeometry();
            //packed.Texturing = ifs.texCoordinate != null;// || parentShape.texturingEnabled;

            coordinate = (Coordinate)ils.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(Coordinate));

            packed.RGBA             = false;
            packed.RGB              = false;
            packed.Coloring         = false;
            packed.generateColorMap = false;

            if (coordinate != null && !string.IsNullOrEmpty(ils.coordIndex))
            {
                packed._indices = X3DTypeConverters.ParseIndicies(ils.coordIndex);
                packed._coords  = X3DTypeConverters.MFVec3f(coordinate.point);

                if (ils.coordIndex.Contains(RESTART_INDEX.ToString()))
                {
                    packed.restartIndex = RESTART_INDEX;
                }

                packed.vertexStride = 2;

                packed.Interleave();
            }

            return(packed);
        }
        public override void Load()
        {
            base.Load();

            int i;

            // The keyValue field and value_changed events are defined in RGB colour space.
            KeyValues = X3DTypeConverters.MFVec3f(this.keyValue);

            if (KeyValues.Length > Keys.Length)
            {
                Console.WriteLine("[Warning] ColorInterpolator : The number of colours in the keyValue field should be equal to the number of key frames in the key field");
            }

            // OPTIMISE
            for (i = 0; i < Keys.Length; i++)
            {
                if (i >= KeyValues.Length)
                {
                    map[Keys[i]] = Vector3.Zero;
                }
                else
                {
                    map[Keys[i]] = KeyValues[i];
                }
            }
        }
        public void TestX3DTextMFString()
        {
            string text;

            string[] @strings;

            text     = "\"Textnodeusing\" \"diffuseColorappearance\"";
            @strings = X3DTypeConverters.GetMFString(text);
            Assert.IsTrue(@strings.Length == 2);

            text     = "\"SERIF\"";
            @strings = X3DTypeConverters.GetMFString(text);
            Assert.IsTrue(@strings.Length == 1);

            text     = "\"Text node using\" \"diffuseColor appearance\"";
            @strings = X3DTypeConverters.GetMFString(text);
            Assert.IsTrue(@strings.Length == 2);

            text     = "'Text node using' 'diffuseColor appearance'";
            @strings = X3DTypeConverters.GetMFString(text);
            Assert.IsTrue(@strings.Length == 2);


            text     = "'Text node using' 'diffuseColor \nappearance'";
            @strings = X3DTypeConverters.GetMFString(text);
            Assert.IsTrue(@strings.Length == 2);

            text     = "'Text node     \n  using' '     diffuseColor \nappearance'";
            @strings = X3DTypeConverters.GetMFString(text);
            Assert.IsTrue(@strings.Length == 2);
        }
        public static PackedGeometry Pack(LineSet lineSet)
        {
            PackedGeometry packed;
            Coordinate     coordinate;

            packed = new PackedGeometry();

            coordinate = (Coordinate)lineSet.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(Coordinate));

            packed.RGBA             = false;
            packed.RGB              = false;
            packed.Coloring         = false;
            packed.generateColorMap = false;

            if (coordinate != null)
            {
                packed._coords = X3DTypeConverters.MFVec3f(coordinate.point);

                packed.restartIndex = null;
                packed.vertexStride = 2;
                packed.vertexCount  = lineSet.vertexCount;

                packed.Interleave();
            }

            return(packed);
        }
Exemple #11
0
        public static IndexedLineSet CreateFromVertexSet(List <Vertex> verticies)
        {
            IndexedLineSet ils;
            Coordinate     coord;

            Vector3[] points;
            int[]     indicies;
            int       i;

            ils   = new IndexedLineSet();
            coord = new Coordinate();

            points = verticies.Select(v => v.Position).ToArray();

            i        = -1;
            indicies = verticies.Select(v => ++ i).ToArray();

            coord.point = X3DTypeConverters.ToString(points);

            ils.coordIndex = X3DTypeConverters.ToString(indicies);
            ils.Children.Add(coord);
            ils.PrimativeType = PrimitiveType.Lines;

            return(ils);
        }
        public static PackedGeometry Pack(IndexedFaceSet ifs)
        {
            PackedGeometry    packed;
            TextureCoordinate texCoordinate;
            Coordinate        coordinate;
            Color             colorNode;
            ColorRGBA         colorRGBANode;

            packed = new PackedGeometry();
            //packed.Texturing = ifs.texCoordinate != null;// || parentShape.texturingEnabled;

            texCoordinate = (TextureCoordinate)ifs.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(TextureCoordinate));
            coordinate    = (Coordinate)ifs.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(Coordinate));
            colorNode     = (Color)ifs.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(Color));
            colorRGBANode = (ColorRGBA)ifs.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(ColorRGBA));

            packed.RGBA             = colorRGBANode != null;
            packed.RGB              = colorNode != null;
            packed.Coloring         = packed.RGBA || packed.RGB;
            packed.generateColorMap = packed.Coloring;

            if (packed.RGB && !packed.RGBA)
            {
                packed.color = X3DTypeConverters.Floats(colorNode.color);
            }
            else if (packed.RGBA && !packed.RGB)
            {
                packed.color = X3DTypeConverters.Floats(colorRGBANode.color);
            }

            if (texCoordinate != null && !string.IsNullOrEmpty(ifs.texCoordIndex))
            {
                packed._texIndices = X3DTypeConverters.ParseIndicies(ifs.texCoordIndex);
                packed._texCoords  = X3DTypeConverters.MFVec2f(texCoordinate.point);
                packed.Texturing   = true;
            }

            if (coordinate != null && !string.IsNullOrEmpty(ifs.coordIndex))
            {
                packed._indices = X3DTypeConverters.ParseIndicies(ifs.coordIndex);
                packed._coords  = X3DTypeConverters.MFVec3f(coordinate.point);

                if (!string.IsNullOrEmpty(ifs.colorIndex))
                {
                    packed._colorIndicies = X3DTypeConverters.ParseIndicies(ifs.colorIndex);
                }

                if (ifs.coordIndex.Contains(RESTART_INDEX.ToString()))
                {
                    packed.restartIndex = RESTART_INDEX;
                }

                packed.Interleave();
            }

            return(packed);
        }
        public void LinkShaderSource(string source)
        {
            ShaderSource = X3DTypeConverters.UnescapeXMLValue(source).Trim();

            if (parentShader != null && parentShape != null)
            {
                parentShader.ShaderParts.Add(this);
            }
        }
Exemple #14
0
        public ElevationGrid BuildVaryingHeightMap(int xDimension, int zDimension,
                                                   float xSpacing, float zSpacing,
                                                   bool colorPerVertex,
                                                   ElevationColorSequencerDelegate colorSequencer,
                                                   HeightComputationDelegate geometrySequencer)
        {
            ElevationGrid g          = new ElevationGrid();
            Color         colorNode  = new Color();
            int           numHeights = xDimension * zDimension;
            int           faceIndex  = 0;
            Vector3       color;
            int           coordIndex = 0;

            g.colorPerVertex = colorPerVertex;
            g.xDimension     = xDimension.ToString();
            g.zDimension     = zDimension.ToString();
            g.xSpacing       = xSpacing;
            g.zSpacing       = zSpacing;
            g.height         = string.Empty;
            colorNode.color  = string.Empty;

            Console.WriteLine("Building varying height map (this could take a while)");

            for (int x = 0; x < xDimension; x++)
            {
                for (int z = 0; z < zDimension; z++)
                {
                    if (coordIndex % 4 == 0 && coordIndex > 0)
                    {
                        faceIndex++;
                    }

                    g.height += string.Format(" {0}", geometrySequencer(x, z));

                    if (colorSequencer != null)
                    {
                        color            = colorSequencer(faceIndex, coordIndex, x, z);
                        colorNode.color += X3DTypeConverters.ToString(color) + ", ";
                    }

                    updateProgress(coordIndex, numHeights);

                    coordIndex++;
                }
            }

            colorNode.color = colorNode.color.TrimStart();
            colorNode.color = colorNode.color.Substring(0, colorNode.color.Length - 2);

            g.height = g.height.TrimStart();
            g.Children.Add(colorNode);

            return(g);
        }
 public string ToFriendlyString()
 {
     return(string.Format(
                "Material <ambientIntensity=\"{0}\", diffuse=\"{1}\", emissive=\"{2}\", shininess=\"{3}\", specular=\"{4}\", transparency=\"{5}\">",
                ambientIntensity,
                X3DTypeConverters.ToString(this._diffuseColor),
                X3DTypeConverters.ToString(this._emissiveColor),
                this._shininess,
                X3DTypeConverters.ToString(this._specularColor),
                this._transparency
                ));
 }
Exemple #16
0
        /// <summary>
        /// Updates the field with a new value just in the SceneGraph.
        /// (Changes in the field are picked up by a currrently running X3DProgrammableShaderObject)
        /// </summary>
        public void setFieldValue(string name, object value)
        {
            field field = (field)this.Children
                          .FirstOrDefault(n => n.GetType() == typeof(field) &&
                                          n.getAttribute("name").ToString() == name);

            Type   type;
            object convValue;
            Type   conv;

            try
            {
                type      = X3DTypeConverters.X3DSimpleTypeToManagedType(field.type);
                convValue = Convert.ChangeType(value, type);
                conv      = convValue.GetType();

                if (conv == typeof(int))
                {
                    UpdateField(name, X3DTypeConverters.ToString((int)convValue));
                }
                if (conv == typeof(float))
                {
                    UpdateField(name, X3DTypeConverters.ToString((float)convValue));
                }
                if (conv == typeof(Vector3))
                {
                    UpdateField(name, X3DTypeConverters.ToString((Vector3)convValue));
                }
                if (conv == typeof(Vector4))
                {
                    UpdateField(name, X3DTypeConverters.ToString((Vector4)convValue));
                }
                if (conv == typeof(Matrix3))
                {
                    UpdateField(name, X3DTypeConverters.ToString((Matrix3)convValue));
                }
                if (conv == typeof(Matrix4))
                {
                    UpdateField(name, X3DTypeConverters.ToString((Matrix4)convValue));
                }
            }
            catch
            {
                Console.WriteLine("error");
            }
        }
Exemple #17
0
        public void InitBoundaryPoints(Vector3 origin)
        {
            int[]     colIndicies;
            Vector3[] verticies;
            Vector3[] pointColors;
            int[]     indicies;

            boundaries(origin, new Vector3(1, 0, 0), out pointColors, out colIndicies, out indicies, out verticies);

            var _pb = new PackedGeometry();

            _pb.Coloring       = true;
            _pb._indices       = indicies;
            _pb._coords        = verticies;
            _pb.color          = X3DTypeConverters.Vec3ToFloatArray(pointColors);
            _pb._colorIndicies = colIndicies;
            _pb.restartIndex   = -1;
            _pb.Interleave();
            _handlepb = _pb.CreateHandle();
        }
Exemple #18
0
        public override void Load()
        {
            base.Load();

            int i;

            _keyValues = X3DTypeConverters.Integers(this.keyValue);

            // OPTIMISE
            for (i = 0; i < Keys.Length; i++)
            {
                if (i >= _keyValues.Length)
                {
                    map[Keys[i]] = 0;
                }
                else
                {
                    map[Keys[i]] = _keyValues[i];
                }
            }
        }
Exemple #19
0
        public void SetFieldValueSTR(string name, string value, string x3dType)
        {
            if (HasErrors)
            {
                return;
            }

            object v;
            Type   type;

            v = X3DTypeConverters.StringToX3DSimpleTypeInstance(value, x3dType, out type);

            if (type == typeof(int))
            {
                SetFieldValue(name, (int)v);
            }
            if (type == typeof(float))
            {
                SetFieldValue(name, (float)v);
            }
            if (type == typeof(Vector3))
            {
                SetFieldValue(name, (Vector3)v);
            }
            if (type == typeof(Vector4))
            {
                SetFieldValue(name, (Vector4)v);
            }
            if (type == typeof(Matrix3))
            {
                Matrix3 m = (Matrix3)v;
                SetFieldValue(name, ref m);
            }
            if (type == typeof(Matrix4))
            {
                Matrix4 m = (Matrix4)v;
                SetFieldValue(name, ref m);
            }
        }
        public static PackedGeometry Pack(PointSet pointSet)
        {
            PackedGeometry packed;
            Coordinate     coordinate;
            Color          colorNode;
            ColorRGBA      colorRGBANode;

            packed = new PackedGeometry();

            coordinate    = (Coordinate)pointSet.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(Coordinate));
            colorNode     = (Color)pointSet.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(Color));
            colorRGBANode = (ColorRGBA)pointSet.ChildrenWithAppliedReferences.FirstOrDefault(n => n.GetType() == typeof(ColorRGBA));

            packed.RGBA             = colorRGBANode != null;
            packed.RGB              = colorNode != null;
            packed.Coloring         = packed.RGBA || packed.RGB;
            packed.generateColorMap = packed.Coloring;

            if (packed.RGB && !packed.RGBA)
            {
                packed.color = X3DTypeConverters.Floats(colorNode.color);
            }
            else if (packed.RGBA && !packed.RGB)
            {
                packed.color = X3DTypeConverters.Floats(colorRGBANode.color);
            }

            if (coordinate != null)
            {
                packed._coords = X3DTypeConverters.MFVec3f(coordinate.point);

                packed.restartIndex = null;
                packed.vertexStride = 1;

                packed.Interleave();
            }

            return(packed);
        }
        public void TestURIWithBackupURI()
        {
            string url;

            string[] uris;
            object   resource;
            bool     success;

            url = "\"images/left.png\" \"http://www.web3d.org/x3d/content/examples/Basic/DistributedInteractiveSimulation/images/left.png\"";

            uris = X3DTypeConverters.GetMFString(url);

            Assert.IsTrue(uris.Length == 2);

            success = SceneManager.FetchSingle(uris[0], out resource);
            Assert.IsFalse(success);
            Assert.IsTrue(resource == null);
            // even though the relative address fails with uris[0] when looking on the file system
            // uris[1] should succeed in returning a new copy of the resource from a remote address.

            success = SceneManager.FetchSingle(uris[1], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
        }
        public static bool Fetch(string url_mfstring, out object resource)
        {
            if (X3DTypeConverters.IsMFString(url_mfstring))
            {
                string[] urls = X3DTypeConverters.GetMFString(url_mfstring);

                foreach (string url in urls)
                {
                    if (FetchSingle(url, out resource))
                    {
                        return(true);
                    }
                }
                resource = null;
                return(false);
            }
            else
            {
                return(FetchSingle(url_mfstring, out resource));
            }

            //resource = null;
            //return false;
        }
Exemple #23
0
        public static LineSet CreateFromVertexSet(List<Vertex> verticies, int vertexStride)
        {
            LineSet ils;
            Coordinate coord;
            Vector3[] points;
            int[] indicies;
            int i;

            ils = new LineSet();
            coord = new Coordinate();

            points = verticies.Select(v => v.Position).ToArray();

            i = -1;
            indicies = verticies.Select(v => ++i).ToArray();

            coord.point = X3DTypeConverters.ToString(points);

            ils.vertexCount = vertexStride;
            ils.Children.Add(coord);
            ils.PrimativeType = PrimitiveType.LineLoop;

            return ils;
        }
        public override void CollectGeometry(
            RenderingContext rc,
            out GeometryHandle handle,
            out BoundingBox bbox,
            out bool Coloring,
            out bool Texturing)
        {
            List <Vertex> geometry;


            handle = GeometryHandle.Zero;
            bbox   = BoundingBox.Zero;



            parentShape       = GetParent <Shape>();
            colorNode         = (Color)this.Children.FirstOrDefault(n => n.GetType() == typeof(Color));
            colorRGBANode     = (ColorRGBA)this.Children.FirstOrDefault(n => n.GetType() == typeof(ColorRGBA));
            texCoordinateNode = (TextureCoordinate)this.Children.FirstOrDefault(n => n.GetType() == typeof(TextureCoordinate));

            RGBA             = colorRGBANode != null;
            RGB              = colorNode != null;
            coloring         = RGBA || RGB;
            generateColorMap = coloring;

            texturing           = texCoordinateNode != null || parentShape.texturingEnabled;
            generateTexCoordMap = texturing;

            Coloring  = coloring;
            Texturing = texturing;

            if (RGB && !RGBA)
            {
                color = X3DTypeConverters.Floats(colorNode.color);
            }
            else if (RGBA && !RGB)
            {
                color = X3DTypeConverters.Floats(colorRGBANode.color);
            }

            _isLoaded = true;


            ////
            ////
            ////



            if (construct)
            {
                float sx = this.xSpacing;
                float sz = this.zSpacing;

                IConstructionSet      constructionSet;
                IPerlinNoiseGenerator perlinProvider;
                Bitmap largePerlinImage;

                constructionSet = SceneManager.GetCurrentConstructionSet();
                perlinProvider  = constructionSet.GetPerlinNoiseProvider();

                ElevationGrid generated = constructionSet.ElevationBuilder.BuildHeightmapFromGenerator(
                    rc,
                    perlinProvider,
                    out largePerlinImage, 40, 40, 20, 20, 20); // build a rather large height map

                largePerlinImage.Dispose();

                Color genColorNode = (Color)generated.Children.FirstOrDefault(n => n.GetType() == typeof(Color));
                this.RGB             = coloring = generateColorMap = true;
                this.height          = generated.height;
                this.color           = X3DTypeConverters.Floats(genColorNode.color);
                this.colorPerVertex  = generated.colorPerVertex;
                this.normalPerVertex = generated.normalPerVertex;
                this.Children        = generated.Children;
                this.xSpacing        = generated.xSpacing;
                this.zSpacing        = generated.zSpacing;
                this.xDimension      = generated.xDimension;
                this.zDimension      = generated.zDimension;
            }



            if (!this._isLoaded)
            {
                parentShape = GetParent <Shape>();

                texturing           = parentShape.texturingEnabled;
                generateTexCoordMap = texturing && texCoordinateNode == null;

                this._isLoaded = true;
            }


            height_mapping();

            bbox = BoundingBox.CalcBoundingBox(this);


            geometry = BuildElevationGeometryQuads(bbox);

            Buffering.BufferShaderGeometry(geometry, out handle.vbo4, out handle.NumVerticies4);
        }
        //[XmlIgnore]
        //public string ShaderSource;

        #region Rendering Methods

        public override void Load()
        {
            base.Load();

            parentShape  = GetParent <Shape>();
            parentShader = GetParent <ComposedShader>();

            string file;

            string[] mf_urls;

            if (!string.IsNullOrEmpty(ShaderSource))
            {
                LinkShaderSource(ShaderSource);
            }
            else if (Urls != null)
            {
                file = Urls.FirstOrDefault();

                if (!string.IsNullOrEmpty(file))
                {
                    _url = _url.TrimStart();

                    if (_url.StartsWith(X3DTypeConverters.DATA_TEXT_PLAIN))
                    {
                        ShaderSource = _url.Remove(0, X3DTypeConverters.DATA_TEXT_PLAIN.Length).TrimStart();

                        LinkShaderSource(ShaderSource);
                    }
                    else
                    {
                        file = file.Replace("\"", "");
                        file = SceneManager.CurrentLocation + "\\" + file;

                        if (X3DTypeConverters.IsMFString(file))
                        {
                            object resource;

                            mf_urls = X3DTypeConverters.GetMFString(file);

                            foreach (string url in mf_urls)
                            {
                                if (SceneManager.FetchSingle(url, out resource))
                                {
                                    Stream s;

                                    s = (Stream)resource;

                                    StreamReader sr = new StreamReader(s);
                                    ShaderSource = sr.ReadToEnd();

                                    s.Close();

                                    break;
                                }
                            }
                        }
                        else
                        {
                            ShaderSource = File.ReadAllText(file);

                            LinkShaderSource(ShaderSource);
                        }
                    }
                }
            }
        }
Exemple #26
0
        private bool GetTextureImageFromMFString2(string mfstring)
        {
            Rectangle imgRect;

            int[] textureMaxSize;
            int   glTexWidth;
            int   glTexHeight;

            string[] urls;
            object   resource;
            bool     actually_loaded_something;

            if (X3DTypeConverters.IsMFString(mfstring))
            {
                actually_loaded_something = false;
                urls = X3DTypeConverters.GetMFString(mfstring);

                foreach (string url in urls)
                {
                    if (SceneManager.FetchSingle(url, out resource))
                    {
                        Stream s;

                        s          = (Stream)resource;
                        this.image = new Bitmap(s);
                        s.Close();
                        actually_loaded_something = true;
                        break;
                    }
                }

                if (!actually_loaded_something)
                {
                    this.image = Properties.Resources.ErrorTexture;
                }
            }
            else
            {
                this.image = new Bitmap(mfstring);
            }

            if (this.image == null)
            {
                return(false);
            }

            /*	Get the maximum texture size supported by OpenGL: */
            textureMaxSize = new int[] { 0 };
            GL.GetInteger(GetPName.MaxTextureSize, textureMaxSize);
            //gl.GetInteger(OpenGL.GL_MAX_TEXTURE_SIZE,textureMaxSize);

            /*	Find the target width and height sizes, which is just the highest
             *	posible power of two that'll fit into the image. */
            glTexWidth  = textureMaxSize[0];
            glTexHeight = textureMaxSize[0];
            for (int size = 1; size <= textureMaxSize[0]; size *= 2)
            {
                if (image.Width < size)
                {
                    glTexWidth = size / 2;
                    break;
                }
                if (image.Width == size)
                {
                    glTexWidth = size;
                }
            }

            for (int size = 1; size <= textureMaxSize[0]; size *= 2)
            {
                if (image.Height < size)
                {
                    glTexHeight = size / 2;
                    break;
                }
                if (image.Height == size)
                {
                    glTexHeight = size;
                }
            }

            if (image.Width != glTexWidth || image.Height != glTexHeight)
            {
                /* Scale the image according to OpenGL requirements */
                Image newImage = image.GetThumbnailImage(glTexWidth, glTexHeight, null, IntPtr.Zero);

                image.Dispose();
                image = (Bitmap)newImage;
            }

            //if(file.ToLower().EndsWith(".bmp")) {
            image.RotateFlip(RotateFlipType.RotateNoneFlipY); //TODO: figure out more efficient code

            /* Another way to rotate texture on draw()
             * gl.MatrixMode(OpenGL.GL_TEXTURE);
             * gl.LoadIdentity();
             * gl.Scale(1.0f,-1.0f,1.0f);
             * gl.MatrixMode(OpenGL.GL_MODELVIEW);
             */
            //}
            imgRect   = new Rectangle(0, 0, image.Width, image.Height);
            pixelData = image.LockBits(imgRect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            pTexImage = pixelData.Scan0;
            Width     = image.Width;
            Height    = image.Height;
            _type     = InternalImageType.WindowsHandle;

            return(true);
        }
Exemple #27
0
        public override void Load()
        {
            base.Load();

            int            i;
            int            a, b;
            PackedGeometry _pack;

            cubeHandle  = GeometryHandle.Zero;
            innerHandle = GeometryHandle.Zero;
            outerHandle = GeometryHandle.Zero;

            generateCube = !(string.IsNullOrEmpty(frontUrl) || string.IsNullOrEmpty(backUrl) ||
                             string.IsNullOrEmpty(topUrl) || string.IsNullOrEmpty(bottomUrl) ||
                             string.IsNullOrEmpty(leftUrl) || string.IsNullOrEmpty(rightUrl));

            //TODO: replace cube sides that arent available with transparent sides

            generateSkyAndGround = !(string.IsNullOrEmpty(groundColor) || string.IsNullOrEmpty(skyColor) ||
                                     string.IsNullOrEmpty(groundAngle) || string.IsNullOrEmpty(skyAngle));


            // TODO: later render both skydome and skybox together
            // Alpha values in skybox should provide a way to see through to skydome.
            // Skycolor sphere should be slightly larger than groundcolor hemisphere
            // and finally skybox should fit and be smaller than groundcolor hemisphere.

            if (generateSkyAndGround)
            {
                // Sphere
                // interpolate colors from groundColor and skyColor over hemispheres using specified sky and ground angles
                this.groundColors = X3DTypeConverters.MFVec3f(groundColor);
                this.groundAngles = X3DTypeConverters.Floats(groundAngle);
                this.skyColors    = X3DTypeConverters.MFVec3f(skyColor);
                this.skyAngles    = X3DTypeConverters.Floats(skyAngle);

                // Assign colors with matching angles
                colors = new Vector3[groundColors.Length + skyColors.Length];
                for (i = 0; i < skyColors.Length; i++)
                {
                    colors[i] = skyColors[i];
                }
                for (i = skyColors.Length; i < skyColors.Length + groundColors.Length; i++)
                {
                    colors[i] = groundColors[i - skyColors.Length];
                }
                angles    = new float[groundAngles.Length + skyAngles.Length + 2];
                angles[0] = 0;
                for (i = 0; i < skyAngles.Length; i++)
                {
                    angles[i + 1] = skyAngles[i];
                }
                angles[skyAngles.Length + 1] = 0;
                for (i = 0; i < groundAngles.Length; i++)
                {
                    angles[i + skyAngles.Length + 2] = 1.5f + groundAngles[i];
                }



                groundDivisor = (1.0f / groundColors.Length) * (float)Math.PI; // how many colors divided over 90 degrees (lower hemisphere)
                skyDivisor    = (1.0f / groundColors.Length) * (float)Math.PI; // how many colors divided over 90 degrees (upper hemisphere)

                // SKYDOME
                // outer sphere (sky)

                scaleSky     = Vector3.One * 6.0f;                                             // slightly bigger than ground hemisphere
                _shaderOuter = ShaderCompiler.ApplyShader(BackgroundShader.vertexShaderSource, // Make use of the BackgroundShader for Skydome Linear Interpolation
                                                          BackgroundShader.fragmentShaderSource);
                _shaderOuter.Link();

                List <Vertex> geometryOuterSphere = BuildSphereGeometryQuads(60, Vector3.Zero, 1.0f);
                Buffering.BufferShaderGeometry(geometryOuterSphere, out outerHandle.vbo4, out outerHandle.NumVerticies4);

                min = Vector3.Zero;
                max = Vector3.Zero;
                BoundingBox.CalculateBoundingBox(geometryOuterSphere, out max, out min);
                bboxOuter = max - min;

                // inner hemisphere (ground)

                //scaleGround = Vector3.One * 5.6f;
                //_shaderInner = ShaderCompiler.ApplyShader(BackgroundShader.vertexShaderSource,
                //                                 BackgroundShader.fragmentShaderSource);
                //_shaderInner.Link();

                //List<Vertex> geometryInnerHemisphere = BuildHemisphereGeometryQuads(60, new Vector3(0, 0.0f,0), 1.0f, false);
                //Buffering.BufferShaderGeometry(geometryInnerHemisphere, out innerHandle.vbo4, out innerHandle.NumVerticies4);

                //min = Vector3.Zero;
                //max = Vector3.Zero;
                //BoundingBox.CalculateBoundingBox(geometryInnerHemisphere, out max, out min);
                //bboxInner = max - min;


                skydomeTexture = MakeSkydomeTexture();
            }

            if (generateCube)
            {
                tex_cube = createCubeMapFromURIs();

                // SKYBOX
                // innermost skybox

                scaleCube = Vector3.One * 3.1f;

                _shaderInnerCube = ShaderCompiler.ApplyShader(CubeMapBackgroundShader.vertexShaderSource,
                                                              CubeMapBackgroundShader.fragmentShaderSource);
                _shaderInnerCube.Link();

                _pack           = new PackedGeometry();
                _pack._indices  = _cube.Indices;
                _pack._coords   = _cube.Vertices;
                _pack.Texturing = true;
                //_pack._colorIndicies = _boxGeometry.Colors;
                _pack._texCoords   = _cube.Texcoords;
                _pack.restartIndex = -1;

                _pack.Interleave();

                // BUFFER GEOMETRY
                cubeHandle = _pack.CreateHandle();
            }
        }
        public void TestFileSystemURIs()
        {
            SceneManager.CurrentLocation = X3DExamplesDirectory;

            string url;

            string[] uris;
            object   resource;
            bool     success;

            // TEST MFString PARSING
            // uris formatted with double quotes
            url  = "spectrum.jpg";
            uris = X3DTypeConverters.GetMFString(url);
            Assert.IsTrue(uris.Length == 1);
            Assert.AreEqual(uris[0], "spectrum.jpg");
            url  = "\"spectrum.jpg\"";
            uris = X3DTypeConverters.GetMFString(url);
            Assert.IsTrue(uris.Length == 1);
            Assert.AreEqual(uris[0], "spectrum.jpg");

            url  = "Background\\texture\\earth.jpg";
            uris = X3DTypeConverters.GetMFString(url);
            Assert.IsTrue(uris.Length == 1);
            Assert.AreEqual(uris[0], "Background\\texture\\earth.jpg");
            url  = "\"Background\\texture\\earth.jpg\"";
            uris = X3DTypeConverters.GetMFString(url);
            Assert.IsTrue(uris.Length == 1);
            Assert.AreEqual(uris[0], "Background\\texture\\earth.jpg");

            // uris formatted with single quotes
            url  = "'spectrum.jpg'";
            uris = X3DTypeConverters.GetMFString(url);
            Assert.IsTrue(uris.Length == 1);
            Assert.AreEqual(uris[0], "spectrum.jpg");

            url  = "'Background\\texture\\earth.jpg'";
            uris = X3DTypeConverters.GetMFString(url);
            Assert.IsTrue(uris.Length == 1);
            Assert.AreEqual(uris[0], "Background\\texture\\earth.jpg");


            // TEST MFString URI fetching
            url     = "spectrum.jpg";
            success = SceneManager.FetchSingle(url, out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            url     = "\"spectrum.jpg\"";
            success = SceneManager.FetchSingle(url, out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            url     = "Background\\texture\\earth.jpg";
            success = SceneManager.FetchSingle(url, out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);

            SceneManager.CurrentLocation = X3DExamplesDirectory + "Background\\";
            url     = "'texture\\generic\\BK.png' 'texture\\generic\\DN.png' 'texture\\generic\\FR.png' 'texture\\generic\\LF.png' 'texture\\generic\\RT.png' 'texture\\generic\\UP.png'";
            uris    = X3DTypeConverters.GetMFString(url);
            success = SceneManager.FetchSingle(uris[0], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            success = SceneManager.FetchSingle(uris[1], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            success = SceneManager.FetchSingle(uris[2], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            success = SceneManager.FetchSingle(uris[3], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            success = SceneManager.FetchSingle(uris[4], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
            success = SceneManager.FetchSingle(uris[5], out resource);
            Assert.IsTrue(success);
            Assert.IsTrue(resource is Stream);
        }
Exemple #29
0
        public ElevationGrid BuildHeightmapFromTexture(
            float xSpacing, float zSpacing,
            Bitmap texture,
            float maxHeight = 1.0f)
        {
            ElevationGrid g = new ElevationGrid();
            Color         colorNode = new Color();
            int           xDimension, zDimension;
            int           numHeights;
            int           faceIndex  = 0;
            int           coordIndex = 0;
            float         height;

            System.Drawing.Color color;
            Vector3 vColor;
            Vector3 vNTSCConversionWeight;
            float   grayscale;

            g.colorPerVertex = true;
            g.xSpacing       = xSpacing;
            g.zSpacing       = zSpacing;
            g.height         = string.Empty;
            colorNode.color  = string.Empty;

            xDimension = texture.Width;
            zDimension = texture.Height;

            numHeights = xDimension * zDimension;

            g.xDimension = xDimension.ToString();
            g.zDimension = zDimension.ToString();

            Console.WriteLine("Building height map from texture (this could take a while)");

            for (int x = 0; x < xDimension; x++)
            {
                for (int z = 0; z < zDimension; z++)
                {
                    if (coordIndex % 4 == 0 && coordIndex > 0)
                    {
                        faceIndex++;
                    }

                    color = texture.GetPixel(x, z);


                    // Convert to grayscale using NTSC conversion weights
                    vColor = new Vector3(color.R / 255f, color.G / 255f, color.B / 255f);
                    vNTSCConversionWeight = new Vector3(0.299f, 0.587f, 0.114f);
                    grayscale             = Vector3.Dot(vColor, vNTSCConversionWeight);


                    // Convert color to height value
                    height = (float)(grayscale) * maxHeight;

                    g.height        += string.Format(" {0}", height);
                    colorNode.color += X3DTypeConverters.ToString(vColor) + ", ";

                    updateProgress(coordIndex, numHeights);

                    coordIndex++;
                }
            }

            colorNode.color = colorNode.color.Trim();
            colorNode.color = colorNode.color.Substring(0, colorNode.color.Length - 2);

            g.height = g.height.TrimStart();
            g.Children.Add(colorNode);

            return(g);
        }
        public override void Load()
        {
            base.Load();

            Keys = X3DTypeConverters.Floats(this.key);
        }