コード例 #1
0
    public static List <Module> StringToModuleList(string s, LSystem l)
    {
        List <Module> mods     = new List <Module>();
        int           modIndex = -1;

        for (int i = 0; i < s.Length; ++i)
        {
            switch (s[i])
            {
            case '(': string sParams = s.Substring(i + 1, s.IndexOf(')', i) - (i + 1)); /*Debug.Log(sParams);*/ ParseParams(sParams, mods[modIndex], l); i += sParams.Length + 1;  break;  //trying to ignore brackets!

            default: mods.Add(new Module(s[i])); ++modIndex; break;
            }
        }
        return(mods);
    }
コード例 #2
0
 public virtual GLEx Reset(float red, float green, float blue, float alpha)
 {
     if (isClosed)
     {
         return(this);
     }
     GLUtils.SetClearColor(batch.gl, red, green, blue, alpha);
     this.SetFont(LSystem.GetSystemGameFont());
     this.lastBrush.baseColor  = LColor.DEF_COLOR;
     this.lastBrush.fillColor  = LColor.DEF_COLOR;
     this.lastBrush.baseAlpha  = 1f;
     this.lastBrush.patternTex = null;
     this.SetBlendMode(BlendMethod.MODE_NORMAL);
     this.ResetLineWidth();
     return(this);
 }
コード例 #3
0
ファイル: Model.cs プロジェクト: antmillar/LSystemEvolver
    //generates a mesh from a l system ruleset
    public Mesh MeshFromRuleset(int idx)
    {
        //create L system
        LSystem ls            = new LSystem(_rulesets[idx]._axiom, _iterationCount, _rulesets[idx]);
        string  lSystemOutput = ls.Generate();

        //use turtle to create mesh of L system
        Turtle turtle = new Turtle(_rulesets[idx]._angle);

        turtle.Decode(lSystemOutput);
        turtle.CreateMesh();

        Mesh mesh = turtle._finalMesh;

        return(mesh);
    }
コード例 #4
0
ファイル: Animation.cs プロジェクト: zx8326123/LGame
 /**
  * 返回当前动画图象
  *
  * @return
  */
 public virtual LTexture GetSpriteImage()
 {
     if (size == 0)
     {
         return(null);
     }
     else
     {
         LTexture texture = GetFrame(currentFrameIndex).image;
         if (!texture.isLoaded)
         {
             LSystem.Load(new inner_load(texture));
         }
         return(texture);
     }
 }
コード例 #5
0
    public void SubmitRatings()
    {
        RatingSystem.SubmitRatings();

        // IMPORTANT: Use the new List<bool> isStarred to determine which LSystem's have been selected by the player
        // the index in isStarred corresponds to the index in lSystems
        //Debug.Log("creating wrapper list...");
        List <LSystemWrapper> wrappers = new List <LSystemWrapper>();

        for (int i = 0; i < RatingSystem.lSystems.Count; i++)
        {
            //Debug.Log("in loop i=" + i);
            LSystem lSystem = RatingSystem.lSystems[i];
            //Debug.Log("got lSystem");
            LSystemWrapper wrapper       = new LSystemWrapper();
            string[]       axiomAndRules = LSystem.Encode(lSystem).Split('~');
            //Debug.Log("created axiomAndRules");
            wrapper.Axiom = axiomAndRules[0];
            //Debug.Log("set Axiom");
            wrapper.Rules = axiomAndRules[1];
            // Debug.Log("set Rules");
            wrapper.IsStarred = RatingSystem.isStarred[i];
            //Debug.Log("set isStarred");
            wrapper.PopulationId = SqlConnection.PopulationId.Value;
            // Debug.Log("set PopulationId");
            wrappers.Add(wrapper);
        }
        //Debug.Log("finished creating wrapper list");

        Debug.Log("started coroutine");
        SqlManager.SqlManagerInstance.StartCoroutine(SqlConnection.PostRating(wrappers.ToArray(), () =>
        {
            // keep some levels (starred ones?)

            for (int i = 0; i < RatingSystem.MAX_LSYSTEMS; ++i)
            {
                // add starred level to kept list
                if (RatingSystem.isStarred[i])
                {
                    RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(RatingSystem.lSystems[i]));
                }
            }
            // TODO: MUST HAVE A BACKUP PLAN IF PLAYER DOES NOT STAR ENOUGH LEVELS
            int numLSystemsNeeded = RatingSystem.MAX_LSYSTEMS - RatingSystem.keptForEvolution.Count;
            SqlManager.SqlManagerInstance.StartCoroutine(SqlConnection.GetPopulation((int)(numLSystemsNeeded * 0.8f), GetPopulationCallBack));
        }));
    }
コード例 #6
0
        public static int RemoveTexture(string name, bool remove)
        {
            LTexture texture = (LTexture)CollectionUtils.Get(lazyTextures, name);

            if (texture != null)
            {
                if (texture.refCount <= 0)
                {
                    if (remove)
                    {
                        lock (lazyTextures)
                        {
                            CollectionUtils.Remove(lazyTextures, name);
                        }
                    }
                    if (!texture.isClose)
                    {
                        LSystem.Load(new DeleteUpdate(texture));
                        if (texture.imageData != null && texture.parent == null)
                        {
                            //XNA环境无需分别处理
                            //if (texture.imageData.fileName == null)
                            //{
                            if (texture.imageData.buffer != null)
                            {
                                texture.imageData.buffer.Dispose();
                                texture.imageData.buffer = null;
                            }
                            texture.imageData = null;
                            // }
                        }
                        if (texture.childs != null)
                        {
                            texture.childs.Clear();
                            texture.childs = null;
                        }
                    }
                }
                else
                {
                    texture.refCount--;
                }
                return(texture.refCount);
            }
            return(-1);
        }
コード例 #7
0
    // private List<GameObject> tempLevelButtons;


    public void InitializeLSystems(LSystemWrapper[] retrievedLSystems)
    {
        int retrieved = retrievedLSystems?.Length ?? 0;

        for (int i = 0; i < RatingSystem.MAX_LSYSTEMS; i++)
        {
            if (i < retrieved)
            {
                RatingSystem.lSystems.Add(LSystem.Decode(retrievedLSystems[i].GetString()));
            }
            else
            {
                RatingSystem.lSystems.Add(new LSystem(16, 3, 0.2f));
            }
            RatingSystem.GenerateXMLs(i, 5);
        }
    }
コード例 #8
0
 private void LoadFont()
 {
     if (!isLoaded)
     {
         SpriteFont pFont = (SpriteFont)CollectionUtils.Get(baseFonts, faceName);
         if (pFont == null)
         {
             Font_Updateable font = new Font_Updateable(this);
             LSystem.Load(font);
         }
         else
         {
             this.spriteFont = pFont;
         }
         isLoaded = true;
     }
 }
コード例 #9
0
        internal virtual void Call(Level level, string msg, System.Exception e)
        {
            if (LSystem.IsConsoleLog())
            {
                if (collector != null)
                {
                    collector.Logged(level, msg, e);
                }
                if (level.id >= minLevel.id)
                {
                    CallNativeLog(level, msg, e);
                    LGame game = LSystem.Base;
                    if (game != null)
                    {
                        LSetting setting = game.setting;
                        // 待实现GLEx

                        /*  LProcess process = LSystem.GetProcess();
                         * if (process != null && (setting.isDebug || setting.isDisplayLog))
                         * {
                         *    LColor color = LColor.white;
                         *    if (level.id > Level.INFO.id)
                         *    {
                         *        color = LColor.red;
                         *    }
                         *    if (process != null)
                         *    {
                         *        if (e == null)
                         *        {
                         *            process.addLog(msg, color);
                         *        }
                         *        else
                         *        {
                         *            process.addLog(msg + " [ " + e.getMessage() + " ] ", color);
                         *        }
                         *    }
                         */
                    }
                }
            }
            if (e != null)
            {
                OnError(e);
            }
        }
コード例 #10
0
ファイル: SpriteBatch.cs プロジェクト: vb0067/LGame
        public void DrawArc(float x1, float y1, float width, float height,
                            int segments, float start, float end)
        {
            while (end < start)
            {
                end += 360;
            }
            float cx   = x1 + (width / 2.0f);
            float cy   = y1 + (height / 2.0f);
            int   step = 360 / segments;

            int hashCode = 1;

            hashCode = LSystem.Unite(hashCode, x1);
            hashCode = LSystem.Unite(hashCode, y1);
            hashCode = LSystem.Unite(hashCode, width);
            hashCode = LSystem.Unite(hashCode, height);
            hashCode = LSystem.Unite(hashCode, segments);
            hashCode = LSystem.Unite(hashCode, start);
            hashCode = LSystem.Unite(hashCode, end);
            hashCode = LSystem.Unite(hashCode, color.PackedValue);
            SubmitDraw();
            XNAPolygon poly = (XNAPolygon)CollectionUtils.Get(polyLazy, hashCode);

            if (poly == null)
            {
                poly             = new XNAPolygon(GLEx.device);
                poly.Stroke      = color;
                poly.StrokeWidth = 1;
                for (float a = start; a < (end + step); a += step)
                {
                    float ang = a;
                    if (ang > end)
                    {
                        ang = end;
                    }
                    float x = (cx + (MathUtils.Cos(MathUtils.ToRadians(ang)) * width / 2.0f));
                    float y = (cy + (MathUtils.Sin(MathUtils.ToRadians(ang)) * height / 2.0f));
                    poly.AddPoint(new Vector2(x, y));
                }
                CollectionUtils.Put(polyLazy, hashCode, poly);
            }
            poly.Draw(batch);
            idx++;
        }
コード例 #11
0
        public static Spline Calculate_M_i(double[] x, double[] y)
        {
            if (x.Length != y.Length)
            {
                throw new ArgumentException("y", "Array of function's values must has same length as array of arguments.");
            }

            X = x;
            Y = y;

            Matrix             mainEquations      = PrepareEquations_M_i();
            BoundaryConditions boundaryConditions = GetBoundaryConditions_M_i();

            LSystem      system    = BuildSystem(mainEquations, boundaryConditions);
            VectorColumn solutions = Tridiagonal.Calculate(system);

            return(new Spline(BuildSpline_M_i(solutions), X));
        }
コード例 #12
0
    public void PlantTree(LSystem theSystem)
    {
        lSystem = theSystem;
        lSystem.Generate(gameObject);

        // turn off all branches
        for (int i = 0; i < transform.childCount; i++)
        {
            Transform baseBranch = transform.GetChild(i);

            for (int j = 0; j < baseBranch.childCount; j++)
            {
                baseBranch.GetChild(j).gameObject.SetActive(j == 0);
            }

            baseBranch.gameObject.SetActive(false);
        }
    }
コード例 #13
0
    // Use this for initialization
    void Awake()
    {
        seed = System.DateTime.Now.Millisecond;
        Random.InitState(seed);

        Dictionary <string, List <Rule> > grammar = new Dictionary <string, List <Rule> >();

        grammar["T"] = new List <Rule>();
        grammar["T"].Add(new Rule(1.0f, "A[#T]T"));
        grammar["A"] = new List <Rule>();
        grammar["A"].Add(new Rule(0.6f, "AA"));
        grammar["A"].Add(new Rule(0.4f, "A"));

        LSystem LS = new LSystem("T", grammar);

        ll = LS.DoIterations(UnityEngine.Random.Range(3, 7));
        DoTurtle(0);
    }
コード例 #14
0
        public LColor GetColor(float r, float g, float b, float a)
        {
            int hashCode = 1;

            hashCode = LSystem.Unite(hashCode, r);
            hashCode = LSystem.Unite(hashCode, g);
            hashCode = LSystem.Unite(hashCode, b);
            hashCode = LSystem.Unite(hashCode, a);
            LColor color = (LColor)CollectionUtils.Get(colorMap, hashCode);

            if (color == null)
            {
                color = new LColor(r, g, b, a);
                CollectionUtils.Put(colorMap, hashCode
                                    , color);
            }
            return(color);
        }
コード例 #15
0
 public LSystemCurveNode()
 {
     LSystem = new LSystem()
     {
         Rules = new List <LSystemRule>()
         {
             new LSystemRule()
             {
                 Input  = 'F',
                 Output = "F-F++F-F"
             }
         },
         Current = "F"
     };
     Theta = Mathf.Pi / 4;
     LengthMultiplicator = 0.6f;
     InitialRotation     = Mathf.Pi / 2;
 }
コード例 #16
0
ファイル: Font.cs プロジェクト: zhangxin8105/LGame
 public Font(string name, Style style, float size)
 {
     if (LSystem.IsMobile())
     {
         if (name != null)
         {
             string familyName = name.ToLower();
             if (familyName.Equals("serif") || familyName.Equals("timesroman"))
             {
                 this.name = "serif";
             }
             else if (familyName.Equals("sansserif") || familyName.Equals("helvetica"))
             {
                 this.name = "sans-serif";
             }
             else if (familyName.Equals("monospaced") || familyName.Equals("courier") ||
                      familyName.Equals("dialog") || familyName.Equals("黑体"))
             {
                 this.name = "monospace";
             }
             else
             {
                 this.name = name;
             }
         }
         else
         {
             this.name = "monospace";
         }
     }
     else
     {
         this.name = name;
     }
     this.style = style;
     if (size % 2 == 0)
     {
         this.size = size;
     }
     else
     {
         this.size = size + 1;
     }
 }
コード例 #17
0
    void Start()
    {
        // Look up so we rotate the tree structure
        transform.Rotate(Vector3.right * -90.0f);
        // Rules can be applied in an inspector, once game is started all information is
        // taken from an editor
        if (ruleChars != null)
        {
            ruleset = new Rule[ruleChars.Length];
            for (int i = 0; i < ruleChars.Length; i++)
            {
                ruleset[i] = new Rule(ruleChars[i], ruleStrings[i]);
            }
        }
        // Create the L-System and a new Turtle
        lsystem = new LSystem(axiom, ruleset);

        turtle = new Turtle(startRadius, treeRoundness, lsystem.GetAlphabet(), length, angleX, angleY, gameObject);
    }
コード例 #18
0
        public static LTextureBatch BindBatchCache(int index,
                                                   int texId, LTexture texture)
        {
            if (batchPools.Count > 128)
            {
                ClearBatchCaches();
            }
            int           key    = LSystem.Unite(index, texId);
            LTextureBatch pBatch = (LTextureBatch)CollectionUtils.Get(batchPools, key);

            if (pBatch == null)
            {
                lock (batchPools) {
                    pBatch = new LTextureBatch(texture);
                    CollectionUtils.Put(batchPools, key, pBatch);
                }
            }
            return(pBatch);
        }
コード例 #19
0
ファイル: StatusBar.cs プロジェクト: zx8326123/LGame
        public LTexture LoadBarColor(LColor c1, LColor c2, LColor c3)
        {
            if (colors.Count > 10)
            {
                lock (colors)
                {
                    foreach (LTexture tex2d in colors.Values)
                    {
                        if (tex2d != null)
                        {
                            tex2d.Destroy();
                        }
                    }
                    colors.Clear();
                }
            }
            int hash = 1;

            hash = LSystem.Unite(hash, c1.GetRGB());
            hash = LSystem.Unite(hash, c2.GetRGB());
            hash = LSystem.Unite(hash, c3.GetRGB());
            LTexture texture = null;

            lock (colors)
            {
                texture = (LTexture)CollectionUtils.Get(colors, hash);
            }
            if (texture == null)
            {
                LImage    image = LImage.CreateImage(8, 8, false);
                LGraphics g     = image.GetLGraphics();
                g.SetColor(c1);
                g.FillRect(0, 0, 4, 4);
                g.SetColor(c2);
                g.FillRect(4, 0, 4, 4);
                g.SetColor(c3);
                g.FillRect(0, 4, 4, 4);
                g.Dispose();
                texture = image.GetTexture();
                CollectionUtils.Put(colors, hash, texture);
            }
            return(this.texture = texture);
        }
コード例 #20
0
    public void ConstructProceduralTree(LSystem lSystem, int iterations, float branchRotateAngle, float branchBendAngle, float branchLengthDefault, float branchDefaultWidth, float taperWidth, float taperHeight, Vector3 bias, float biasStrength, GameObject branchBody, GameObject leafBody)
    {
        this.lSystem             = lSystem;
        this.iterations          = iterations;
        this.branchRotateAngle   = branchRotateAngle;
        this.branchBendAngle     = branchBendAngle;
        this.branchLengthDefault = branchLengthDefault;
        this.branchDefaultWidth  = branchDefaultWidth;
        this.taperWidth          = taperWidth;
        this.taperHeight         = taperHeight;
        this.branchBody          = branchBody;
        this.leafBody            = leafBody;
        this.bias         = bias;
        this.biasStrength = biasStrength;


        IterateDNA();
        DrawTree();
    }
コード例 #21
0
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            this.Services.AddService(typeof(SpriteBatch), spriteBatch);

            system = new TreeSystem();

            turtle = new Turtle(this);
            turtle.Operations.Add('a', () => turtle.Draw(dist));
            turtle.Operations.Add('b', () => turtle.Draw(dist));
            turtle.Operations.Add('m', () => turtle.Move(dist));
            turtle.Operations.Add('-', () => turtle.Turn(MathHelper.ToRadians(-angle)));
            turtle.Operations.Add('+', () => turtle.Turn(MathHelper.ToRadians(angle)));
            turtle.Operations.Add('[', () => { turtle.Push(); turtle.Turn(MathHelper.ToRadians(-angle)); });
            turtle.Operations.Add(']', () => { turtle.Pop(); turtle.Turn(MathHelper.ToRadians(angle)); });
            turtle.Drawings.Add(system.Get(level, 1));

            base.LoadContent();
        }
コード例 #22
0
ファイル: MonoGameAssets.cs プロジェクト: zhangxin8105/LGame
 public override string GetTextSync(string path)
 {
     System.Text.StringBuilder sbr = new System.Text.StringBuilder(1024);
     try
     {
         StreamReader reader = new StreamReader(OpenStream(path), JavaSystem.GetEncoding(LSystem.ENCODING));
         string       record = null;
         for (; (record = reader.ReadLine()) != null;)
         {
             sbr.Append(record);
         }
         reader.Close();
     }
     catch (System.Exception ex)
     {
         LSystem.E("file :" + path + " exception:" + ex.Message);
     }
     return(sbr.ToString());
 }
コード例 #23
0
    // Start is called before the first frame update
    private void Start()
    {
        trees = new List <LSystem>();

        for (int i = 0; i < nTrees; i++)
        {
            GameObject EGOParent = new GameObject();
            EGOParent.name = "Tree" + i;
            //EGOParent.transform.position = new Vector3(transform.position.x + Random.Range(i * multiply - 10f, i * multiply + 10f), 0.0f, transform.position.z + Random.Range(i * multiply - 10f, i * multiply + 10f));
            Vector2 Randompos = Random.insideUnitCircle * nTrees * multiply;
            EGOParent.transform.position = new Vector3(Randompos.x, 0.0f, Randompos.y);
            LSystem newLS = Instantiate(prefab, EGOParent.transform);
            newLS.transform.localPosition = Vector3.zero;
            newLS.branch = this.branch;
            newLS.flower = flowers[Random.Range(0, flowers.Count)];
            newLS.InitialiseRandom();
            trees.Add(newLS);
        }
    }
コード例 #24
0
    /* ----------
     * Axiom: A
     * Rules:
     * A --> L B F R A F A R F B L
     * B --> R A F L B F B L F A R
     * ---------
     * F=forward, L=turn left, R=turn right
     *
     **/
    public static List <Module> Generate(int aOrder)
    {
        LSystemParser parser = new LSystemParser();
        LSystem       sys    = parser.ParseSystem(@"
Axiom: A
Rules:
    A --> L; B; F; R; A; F; A; R; F; B; L
    B --> R; A; F; L; B; F; B; L; F; A; R
            ");

        sys.Iterate(aOrder);

        string        last   = "";
        List <Module> result = new List <Module>(sys.symbols.Count);

        // Filter out the symbols "A" and "B" and also remove pointless rotations
        // So an "L" followed by a "R" is pointless so we can remove both.
        foreach (var m in sys.symbols)
        {
            if (m.Name == "L" || m.Name == "R" || m.Name == "F")
            {
                if ((last == "L" && m.Name == "R") || (last == "R" && m.Name == "L"))
                {
                    result.RemoveAt(result.Count - 1);
                    if (result.Count > 0)
                    {
                        last = result[result.Count - 1].Name;
                    }
                    else
                    {
                        last = "";
                    }
                }
                else
                {
                    result.Add(m);
                    last = m.Name;
                }
            }
        }
        return(result);
    }
コード例 #25
0
    /// <summary>
    /// When its the sql call is done
    /// retrievedLSystems will be null numLSystemsNeeded was 0
    /// </summary>
    /// <param name="retrievedLSystems"></param>
    public void GetPopulationCallBack(LSystemWrapper[] retrievedLSystems)
    {
        //int retrieved = retrievedLSystems?.Length ?? 0;

        //int kept = RatingSystem.keptForEvolution.Count;

        foreach (LSystemWrapper wrapper in retrievedLSystems)
        {
            RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(LSystem.Decode(wrapper.GetString())));
        }

        while (RatingSystem.keptForEvolution.Count < RatingSystem.MAX_LSYSTEMS)
        {
            RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(new LSystem(16, 3, 0.2f)));
        }

        //for (int i = kept; i < RatingSystem.MAX_LSYSTEMS; i++)
        //{
        //    if (i - kept < retrieved)
        //    {
        //        RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(LSystem.Decode(retrievedLSystems[i].GetString())));
        //    }
        //    else
        //    {
        //        RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(new LSystem(10, 3)));
        //    }
        //}
        // keptforevolution will contain a list of levels to run evolution on
        // TODO: Run evolution here and replace RatingSystem.keptForEvolution with the list of newly created LSystems

        RatingSystem.ClearAll();
#if UNITY_WEBGL && !UNITY_EDITOR
        EvolveScene.iterations = 5;
#else
        EvolveScene.iterations = 10;
#endif
        //ABSceneManager.Instance.LoadScene("LevelSelectMenu");
        ABSceneManager.Instance.LoadScene("Evolution");
        //RatingSystem.GenerateXMLs(RatingSystem.CurrentLSystemIndex, 5); // hardcoded height
        //LoadScreenshots(RatingSystem.CurrentLSystemIndex);
        //GenerateNewLevels(RatingSystem.CurrentLSystemIndex);
    }
コード例 #26
0
ファイル: StatusBar.cs プロジェクト: vb0067/LGame
        /// <summary>
        /// ˳ÐòΪ±³¾°£¬Ç°¾°£¬Öо°
        /// </summary>
        ///
        /// <param name="c1"></param>
        /// <param name="c2"></param>
        /// <param name="c3"></param>
        /// <returns></returns>
        public LTexture LoadBarColor(Color c1, Color c2, Color c3)
        {
            if (colors.Count > 10)
            {
                lock (colors)
                {
                    foreach (LTexture tex2d in colors.Values)
                    {
                        if (tex2d != null)
                        {
                            tex2d.Destroy();
                        }
                    }
                    colors.Clear();
                }
            }
            int hash = 1;

            hash = LSystem.Unite(hash, c1.PackedValue);
            hash = LSystem.Unite(hash, c2.PackedValue);
            hash = LSystem.Unite(hash, c3.PackedValue);
            LTexture texture_0 = null;

            lock (colors)
            {
                texture_0 = (LTexture)CollectionUtils.Get(colors, hash);
            }
            if (texture_0 == null)
            {
                LPixmap image = new LPixmap(8, 8, true);
                image.SetColor(c1);
                image.FillRect(0, 0, 4, 4);
                image.SetColor(c2);
                image.FillRect(4, 0, 4, 4);
                image.SetColor(c3);
                image.FillRect(0, 4, 4, 4);
                image.Dispose();
                texture_0 = image.Texture;
                CollectionUtils.Put(colors, hash, texture_0);
            }
            return(this.texture = texture_0);
        }
コード例 #27
0
    //  TODO: Change condition too?
    //  Mutates one random rule, changing the successor and probability of that rule.
    public static LSystem Mutation(LSystem l)
    {
        List <string> symbols = new List <string>(blocks.Keys);

        //Get a successor of random width < max width.
        int    succWidth = random.Next(1, l.maxWidth);
        string successor = "";

        for (int s = 0; s < succWidth; s++)
        {
            string nextSymbol = symbols[random.Next(symbols.Count)];
            successor += nextSymbol;
        }

        //Get a probability.
        double probability = random.Next(0, 100) / 100;

        Dictionary <string, Tuple <List <string>, List <double> > > r = l.rules;

        foreach (KeyValuePair <string, Tuple <List <string>, List <double> > > ruleset in l.rules)
        {
            if (ruleset.Value.Item1.Count != 0)
            {
                List <string> newSuccessors    = ruleset.Value.Item1;
                List <double> newProbabilities = ruleset.Value.Item2;

                //  Mutate a random rule
                int randInd = random.Next(0, newSuccessors.Count);
                newSuccessors[randInd]    = successor;
                newProbabilities[randInd] = probability;

                //Rescale probabilities to [0, 1].
                newProbabilities = RescaleWeights(newProbabilities);
                r[ruleset.Key]   = new Tuple <List <string>, List <double> >(new List <string>(newSuccessors), new List <double>(newProbabilities));

                return(new LSystem(r, l.numRules, l.maxWidth));
            }
        }

        Console.WriteLine("Error: Empty rule dictionary.");
        return(new LSystem(r, l.numRules, l.maxWidth));
    }
コード例 #28
0
ファイル: Model.cs プロジェクト: antmillar/LSystemEvolver
    //animates the step by step drawing of the mesh
    public IEnumerator AnimateMesh(int objNum, View view)
    {
        var     ruleSet       = _rulesets[objNum];
        LSystem ls            = new LSystem(ruleSet._axiom, _iterationCount, ruleSet);
        string  lSystemOutput = ls.Generate();

        //use turtle to create mesh of L system
        Turtle turtle = new Turtle(ruleSet._angle);

        turtle.Decode(lSystemOutput);

        for (int i = 0; i < turtle._meshes.Count; i++)
        {
            turtle.PartialMesh(i);

            //view.InstructionsRewrite(turtle._partialInstructions); //writes the turtle instructions to screen (used in video)
            view.MeshRedraw(turtle._partialMesh); //redraws the partial mesh
            yield return(new WaitForSeconds(0.01f));
        }
    }
コード例 #29
0
    // Start is called before the first frame update
    void Start()
    {
        LSystem seed = new LSystem("FA");

        seed.AddRule("A", "![&FA!![^L]]/'[&FA!![^L]]/'[&FA!![^L]]");
        seed.AddRule("F(x)", "F(x*1.2)");
        seed.AddRule("F", "F(.95)/S");
        seed.AddRule("^^^<L>]", "q");
        seed.AddRule("S", "F[^L]");
        seed.AddRule("L", "^^L");
        for (int i = 0; i < 5; i++)
        {
            seed.Grow();
            TreeBuilder(seed.ToString());
            topTurtle.Set(Vector3.zero, Quaternion.LookRotation(Vector3.up, Vector3.back), Vector3.one);
            this.transform.position = new Vector3(0, 0, 5.0f * (i + 1));
            //Debug.Log(seed.ToString());
        }
        //TreeBuilder(seed.ToString());
    }
コード例 #30
0
ファイル: Loon.cs プロジェクト: zhangxin8105/LGame
        public virtual void UpdateViewSizeData(LMode mode)
        {
            if (zoomWidth <= 0)
            {
                zoomWidth = maxWidth;
            }
            if (zoomHeight <= 0)
            {
                zoomHeight = maxHeight;
            }
            LSystem.SetScaleWidth((float)maxWidth / zoomWidth);
            LSystem.SetScaleHeight((float)maxHeight / zoomHeight);
            LSystem.viewSize.SetSize(zoomWidth, zoomHeight);

            StringBuffer sbr = new StringBuffer();

            sbr.Append("Mode:").Append(mode);
            sbr.Append("\nWidth:").Append(zoomWidth).Append(",Height:" + zoomHeight);
            sbr.Append("\nMaxWidth:").Append(maxWidth).Append(",MaxHeight:" + maxHeight);
            JavaSystem.Out.Println(sbr.ToString());
        }
	// Use this for initialization
	void Start ()
	{
		GameObject g1 = new GameObject ("Scope 1");
		g1.transform.parent = this.transform;
		Scope s = new Scope (this.gameObject);
		Scope s1 = new Scope (g1);
		Rule r = new Rule ("A")
			.add (new TranslateOperation (s1, 0, 0, 6))
			.add (new ScaleOperation (s1, 8, 10, 18))
			.add (new InsertOperation (s1, PrimitiveType.Cube))
			.add (new TranslateOperation (s, 6, 0, 0))
			.add (new ScaleOperation (s, 7, 13, 18))
			.add (new InsertOperation (s, PrimitiveType.Cube))
			.add (new TranslateOperation (s, 0, 0, 16))
			.add (new ScaleOperation (s, 8, 15f/2f, 8))
			.add (new InsertOperation (s, PrimitiveType.Cylinder));

			//.add (new TranslateOperation (g3, 8 / 2, 15 / 2, 8 / 2))
			//.add (new TranslateOperation (g3, 0, 0, 16));

		LSystem lsystem = new LSystem (new Axiom("A", null), 1);
		lsystem.add (r)
			.executeRules ();
	}
コード例 #32
0
 void Awake()
 {
     evaluatedCreatures = new List<Creature>();
     sys = new LSystem(PushState, PopState, PrepareState);
 }
コード例 #33
0
ファイル: Turtle.cs プロジェクト: amixtum/lsystem-unity
    void Start()
    {
        this.transform.position = initialPosition;

        lSystemComponent = LSystemObject.GetComponent<LSystem>();

        constructEventActionMap();

        ExecuteSequence(lSystemComponent.GetSequenceFromAxiom(numberOfIterations));
    }
コード例 #34
0
ファイル: DataManager.cs プロジェクト: theorclord/ThesisApp
 public void InitializeNodes()
 {
     LSystem ls = new LSystem();
     RuleCollection rc = new RuleCollection();
     rc.GenerateRules();
     Debug.Log("Size = " + rc.GetCollection().Count);
     int selectedIndex = Random.Range(0, rc.GetCollection().Count);
     LRule r = (LRule)rc.GetCollection()[selectedIndex];
     ls.axiom = r.axiom;
     ls.delta = r.delta;
     // JUST GO THROUGH THE RANDOMLY SELECTED RULE, USE ITS COLLECTION IN THE EXPAND AND INTERPRET
     Debug.Log(r.name);
     ls.expand(r.expandingIterations, r.rules);
     ls.interpret();
 }
コード例 #35
0
	void Start() {
		OsmBuilding building = Data.Instance.buildings [buildingId];
		//float[] points = building.getPolygon ();
		Vector3[] points = building.getPolygonAsVector3 ();
		Scope s = new Scope (this.gameObject);
		Rule r1 = new Rule ("Footprint")
			.add (new ScaleOperation (s, 1, new System.Random().Next(5, 10), 1))
			.add (new SaveOperation(s, "Facades"));
		Rule r2 = new Rule ("Facades")
			.add (new ComputeOperation (s, "sidefaces", "Facade",
										new string[] {
						
										}));
		Rule r3 = new Rule ("Facade")
			.add (new SubdivideOperation (s, "Y",
										new string[] {
											"1r", "0.5", "3.5"
										},
										new string[] {
											"Floors", "Ledge", "Groundfloor"
										}));
		Rule r4 = new Rule("Floors")
			.add(new RepeatOperation(s, "Y", "3", "Floor"));
		Rule r5 = new Rule ("Floor")
			.add (new RepeatOperation (s, "X", "2", "WindowTile"));
		Rule r6 = new Rule("WindowTile")
			.add(new SubdivideOperation(s, "X",
				new string[] {
					"1r", "0.9", "1r"
				},
				new string[] {
					"Wall", "VerticalWindowTile", "Wall"
				}));
		Rule r7 = new Rule("VerticalWindowTile")
			.add(new SubdivideOperation(s, "Y",
				new string[] {
					"1r", "1.55", "1r"
				},
				new string[] {
					"Wall", "Window", "Wall"
				}));
		Rule r8 = new Rule("Window")
			.add(new InsertModelOperation(s, "window"));
		Rule r9 = new Rule ("Groundfloor")
			.add (new SubdivideOperation (s, "X",
			          new string[] {
				"1r", "1.8", "1r"
			},
			          new string[] {
				"WindowTile", "DoorTile", "WindowTile" 
			}));
		Rule r10 = new Rule ("DoorTile")
			.add (new SubdivideOperation (s, "X",
			           new string[] {
				"1r", "2", "1r"
			},
			           new string[] {
				"Wall", "VerticalDoorTile", "Wall"
			}));
		Rule r11 = new Rule ("VerticalDoorTile")
			.add (new SubdivideOperation (s, "Y",
			           new string[] {
					"1r", "3.5"
			},
			           new string[] {
					"Wall", "Door"
			}));
		Rule r12 = new Rule ("Door")
			.add (new InsertModelOperation (s, "door"));

		//.add (new TranslateOperation (g3, 8 / 2, 15 / 2, 8 / 2))
		//.add (new TranslateOperation (g3, 0, 0, 16));
		/*Vector3[] footprint = new Vector3[] {
			new Vector3 (0, 0, 0),
			new Vector3 (10, 0, 0),
			new Vector3 (15, 0, 5),
			new Vector3 (10, 0, 10),
			new Vector3 (0, 0, 10)
		};*/
		Vector3[] footprint = points;
		LSystem lsystem = new LSystem (new Axiom("Footprint", footprint), 10);
		List<Symbol> symbols = 
			lsystem
			.add (r1)
			.add (r2)
			.add (r3)
			.add (r4)
			.add (r5)
			.add (r6)
			.add (r7)
			.add (r8)
			.add (r9)
			.add (r10)
			.add (r11)
			.add (r12)
			.executeRules ();
		
		drawResult (symbols);
	}
コード例 #36
0
    void Start()
    {
        //Randomize generation numbers
        generations = Random.Range(1,generations);

        // Look up so we rotate the tree structure
        transform.Rotate(Vector3.right * -90.0f);
        // Rules can be applied in an inspector, once game is started all information is
        // taken from an editor
        if (ruleChars != null)
        {
            ruleset = new Rule[ruleChars.Length];
            for(int i = 0; i < ruleChars.Length; i++)
            {
                ruleset[i] = new Rule(ruleChars[i], ruleStrings[i]);
            }
        }
        // Create the L-System and a new Turtle
        lsystem = new LSystem(axiom,ruleset);

        turtle = new Turtle(startRadius, treeRoundness, lsystem.GetAlphabet(), length, angleX, angleY, gameObject);

        // Generate the alphabet n(generations) times
        for (int i = 0; i <= generations; i++)
        {
            lsystem.Generate();

            // Adjust turtle ratios
            // (normaly it happens after the skeleton generation,
            // in this case we need to apply it now)
            turtle.ChangeLength(lengthRatio);
            turtle.ChangeWidth(widthRatio);
        }
        // Save current transform position & rotation
        Vector3 currentP = transform.position;
        Quaternion currentR = transform.rotation;

        // Generate the alphabet & pass it to the turtle
        turtle.SetAlphabet(lsystem.GetAlphabet());
        turtle.DrawPlant();

        // Get vector arrays
        GetTreeBranches();
        transform.position = currentP;
        transform.rotation = currentR;

        DestroyTree();
        RenderTree(branches);
    }
コード例 #37
0
    void Start()
    {
        // Look up so we rotate the tree structure
        transform.Rotate(Vector3.right * -90.0f);
        // Rules can be applied in an inspector, once game is started all information is
        // taken from an editor
        if (ruleChars != null)
        {
            ruleset = new Rule[ruleChars.Length];
            for (int i = 0; i < ruleChars.Length; i++)
            {
                ruleset[i] = new Rule(ruleChars[i], ruleStrings[i]);
            }
        }
        // Create the L-System and a new Turtle
        lsystem = new LSystem(axiom, ruleset);

        turtle = new Turtle(startRadius, treeRoundness, lsystem.GetAlphabet(), length, angleX, angleY, gameObject);
    }
コード例 #38
0
    public void Randomize(int seed, bool newTheme = true)
    {
        if (!Application.isPlaying) {
            Debug.LogError ("You may only randomize in play mode.");
            return;
        }

        if (referenceParameters == null) {
            gameObject.SetActive (false);
            var go = Instantiate (gameObject);
            var gen = Instantiate (generator.gameObject);
            gameObject.SetActive (true);
            referenceParameters = go.GetComponent<ObjectPlacer> ();
            referenceGenerator = gen.GetComponent<LSystem> ();
        }

        Rand hash = new Rand (seed);

        RandomizePlacement (hash, newTheme);
        RandomizeColors (hash, newTheme);
        RandomizeTrees (hash, newTheme);

        Place ();
        UpdateGlobals ();
    }
コード例 #39
0
 public Rule(LSystem lsys)
 {
     this.lsys = lsys;
 }