zoukankan      html  css  js  c++  java
  • 2_flyweight, 轻量化模式

    ### instanced rendering.
    send shared data to gpu just once
        mesh, texture, leaves
    push every instance’s unique data
        position, color, scale
    
    With a single draw call, an entire forest grows.
    
    unity3d
        Using instances of a prefab automatically are using the same mesh and material.
    
    
    ### the flyweight pattern
    
    当拥有大量同样的obj时,则需要更多的轻量化
    
    把一个ojb分成两类
        1: intrinsic state, 共享的数据, content—free stuff
        2: extrinsic state, 独有的数据,
    
    example
    
    ```
    intrinsic state: 世界包含若干种地形
    extrinsic state: 不同的位置具有不同的地形,指向相应的地形
    
    class Terrain
    {
    public:
      Terrain(int movementCost,
              bool isWater,
              Texture texture)
      : movementCost_(movementCost),
        isWater_(isWater),
        texture_(texture)
      {}
    
      int getMovementCost() const { return movementCost_; }
      bool isWater() const { return isWater_; }
      const Texture& getTexture() const { return texture_; }
    
    private:
      int movementCost_;
      bool isWater_;
      Texture texture_;
    };
    
    class World
    {
    public:
      World()
      : grassTerrain_(1, false, GRASS_TEXTURE),
        hillTerrain_(3, false, HILL_TEXTURE),
        riverTerrain_(2, true, RIVER_TEXTURE)
      {}
    
    private:
      Terrain grassTerrain_;
      Terrain hillTerrain_;
      Terrain riverTerrain_;
    
      // Other stuff...
    };
    
    void World::generateTerrain()
    {
      // Fill the ground with grass.
      for (int x = 0; x < WIDTH; x++)
      {
        for (int y = 0; y < HEIGHT; y++)
        {
          // Sprinkle some hills.
          if (random(10) == 0)
          {
            tiles_[x][y] = &hillTerrain_;
          }
          else
          {
            tiles_[x][y] = &grassTerrain_;
          }
        }
      }
    
      // Lay a river.
      int x = random(WIDTH);
      for (int y = 0; y < HEIGHT; y++) {
        tiles_[x][y] = &riverTerrain_;
      }
    }
    
    const Terrain& World::getTile(int x, int y) const
    {
      return *tiles_[x][y];
    }
    
    int cost = world.getTile(2, 3).getMovementCost();
    
    
    ```
    ###其他应用
        工厂方法
        对象池
        状态机
  • 相关阅读:
    HDU 5640 King's Cake
    HDU 5615 Jam's math problem
    HDU 5610 Baby Ming and Weight lifting
    WHU1604 Play Apple 简单博弈
    HDU 1551 Cable master 二分
    CodeForces659C Tanya and Toys map
    Codeforces 960E 树dp
    gym 101485E 二分匹配
    Codeforces 961E 树状数组,思维
    Codeforces Round #473 (Div. 2) D 数学,贪心 F 线性基,模板
  • 原文地址:https://www.cnblogs.com/lightlfyan/p/4224373.html
Copyright © 2011-2022 走看看