Exemple #1
0
    public Chunk ChunkColumnGen(Chunk chunk, int x, int z)
    {
        int stoneHeight = Mathf.FloorToInt(stoneBaseHeight);
        stoneHeight += GetNoise(x, 0, z, stoneMountainFrequency, Mathf.FloorToInt(stoneMountainHeight));

        if (stoneHeight < stoneMinHeight)
            stoneHeight = Mathf.FloorToInt(stoneMinHeight);

        stoneHeight += GetNoise(x, 0, z, stoneBaseNoise, Mathf.FloorToInt(stoneBaseNoiseHeight));

        int dirtHeight = stoneHeight + Mathf.FloorToInt(dirtBaseHeight);
        dirtHeight += GetNoise(x, 100, z, dirtNoise, Mathf.FloorToInt(dirtNoiseHeight));

        for (int y = chunk.pos.y; y < chunk.pos.y + Chunk.chunkSize; y++)
        {

            //Get a value to base cave generation on
            int caveChance = GetNoise(x, y, z, caveFrequency, 100); //Add this line

            if (y <= stoneHeight && caveSize < caveChance) //Add caveSize < caveChance
            {
                chunk.SetBlock(x - chunk.pos.x, y - chunk.pos.y, z - chunk.pos.z, new Block());
            }
            else if (y <= dirtHeight && caveSize < caveChance) //Add caveSize < caveChance
            {
                chunk.SetBlock(x - chunk.pos.x, y - chunk.pos.y, z - chunk.pos.z, new BlockGrass());
            }
            else
            {
                chunk.SetBlock(x - chunk.pos.x, y - chunk.pos.y, z - chunk.pos.z, new BlockAir());
            }
        }

        return chunk;
    }
 public static void BuildRenderer(Chunk chunk, BlockPos pos, MeshData meshData, Direction direction, Vector3 ModelSize, Vector3 ConnMeshSizeX, Vector3 ConnMeshSizeY, Vector3 ConnMeshSizeZ, Direction[] Dir)
 {
     MakeStickFace(chunk, pos, meshData, direction, false, ModelSize);
     Debug.Log(Dir.Length);
     if (Dir.Length > 0)
         MakeFenceFace(chunk, pos, meshData, direction, false, ModelSize, ConnMeshSizeX, ConnMeshSizeY, ConnMeshSizeZ, Dir);
 }
Exemple #3
0
        private static void FluidFillLightG(Chunk chunk)
        {
            for (byte x = 0; x < Chunk.WidthInBlocks; x++)
            {
                for (byte z = 0; z < Chunk.LenghtInBlocks; z++)
                {
                    int offset = BlockStorage.BlockIndexByRelativePosition(chunk, x, z);

                    for (byte y = Chunk.MaxHeightIndexInBlocks; y > 0; y--)
                    {
                        var blockIndex = offset + y;

                        if (BlockStorage.Blocks[blockIndex].Type != BlockType.None) // solid blocks can't propagate light.
                            continue;

                        var blockLight = BlockStorage.Blocks[blockIndex].G;
                        if (blockLight < 1) // if block's light value is too low (dark),
                            continue; // just skip it.

                        var propagatedLight = (byte)((blockLight * 9) / 10);

                        PropagateLightG(blockIndex + BlockStorage.XStep, propagatedLight); // propagate light to block in east.
                        PropagateLightG(blockIndex - BlockStorage.XStep, propagatedLight); // propagate light to block in west.
                        PropagateLightG(blockIndex + BlockStorage.ZStep, propagatedLight); // propagate light to block in north.
                        PropagateLightG(blockIndex - BlockStorage.ZStep, propagatedLight); // propagate light to block in south.
                        // DO NOT repropagete to upper block which we don't need to do so and may cause loops!
                        PropagateLightG(blockIndex - 1, propagatedLight);   // propagate light to block down.
                    }
                }
            }
        }
        public IChunk[] GenerateChunk(IEnumerable<IBlockDefinition> blockDefinitions, IPlanet planet, Index2 index)
        {
            IBlockDefinition sandDefinition = blockDefinitions.FirstOrDefault(d => typeof(SandBlockDefinition) == d.GetType());
            ushort sandIndex = (ushort)(Array.IndexOf(blockDefinitions.ToArray(), sandDefinition) + 1);

            IChunk[] result = new IChunk[planet.Size.Z];

            for (int layer = 0; layer < planet.Size.Z; layer++)
                result[layer] = new Chunk(new Index3(index.X, index.Y, layer), planet.Id);

            int part = (planet.Size.Z * Chunk.CHUNKSIZE_Z) / 4;

            for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
            {
                float heightY = (float)Math.Sin((float)(y * Math.PI) / 15f);
                for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
                {
                    float heightX = (float)Math.Sin((float)(x * Math.PI) / 18f);

                    float height = ((heightX + heightY + 2) / 4) * (2 * part);
                    for (int z = 0; z < planet.Size.Z * Chunk.CHUNKSIZE_Z; z++)
                    {
                        if (z < (int)(height + part))
                        {
                            int block = z % (Chunk.CHUNKSIZE_Z);
                            int layer = (int)(z / Chunk.CHUNKSIZE_Z);
                            result[layer].SetBlock(x, y, block, sandIndex);
                        }
                    }
                }
            }

            return result;
        }
 public ChunkDrawData(List<Vector3> vertexlist, List<int> trianglelist, List<Vector2> uvlist, Chunk chnk)
 {
     vertexList = vertexlist;
     triangleList = trianglelist;
     UVList = uvlist;
     chunk = chnk;
 }
 /// <summary>
 /// Serialize a chunk.
 /// </summary>
 /// <param name="chunk">The chunk to serialize.</param>
 /// <param name="chunkIndex">The chunk index.</param>
 public void SerializeChunk(Chunk chunk, Vector2I chunkIndex)
 {
     // NOTE: This should occur in a seperate thread, since terrain serialization isn't high priority.
     // However, care should be taken to consider the situation when a terrain is being serialized in another thread
     // and then a new deserialization request comes in for that chunk. In this case the deserialization thread
     // should block
 }
Exemple #7
0
    public static bool Load(Chunk chunk)
    {

        string saveFile = SaveLocation(chunk.world.worldName);
        saveFile += FileName(chunk.pos);

        if (!File.Exists(saveFile))
            return false;
        try
        {

            IFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(saveFile, FileMode.Open);

            Save save = (Save)formatter.Deserialize(stream);

            //Once the blocks in the save are added they're marked as unmodified so
            //as not to trigger a new save on unload unless new blocks are added.
            for (int i =0; i< save.blocks.Length; i++)
            {
                Block placeBlock = save.blocks[i];
                placeBlock.modified = false;
                chunk.SetBlock(save.positions[i], placeBlock, false);
            }

            stream.Close();
        }
        catch (Exception ex)
        {
            Debug.LogError(ex);
        }


        return true;
    }
Exemple #8
0
        public override void ApplyBiome(Chunk chunk, int groundLevel, int groundOffset, int worldPositionX, int worldPositionZ)
        {
            BlockStorage.Blocks[groundOffset + 1].Type = BlockType.Sand;

            if (groundLevel + 1 > chunk.HighestSolidBlockOffset)
                chunk.HighestSolidBlockOffset = (byte)(groundLevel + 1);
        }
Exemple #9
0
        protected override void GenerateBlocks(Chunk chunk, int worldPositionX, int worldPositionZ)
        {
            var rockHeight = this.GetRockHeight(worldPositionX, worldPositionZ);
            var dirtHeight = this.GetDirtHeight(worldPositionX, worldPositionZ, rockHeight);

            var offset = BlockStorage.BlockIndexByWorldPosition(worldPositionX, worldPositionZ);

            for (int y = Chunk.MaxHeightIndexInBlocks; y >= 0; y--)
            {
                if (y > dirtHeight) // air
                {
                    BlockStorage.Blocks[offset + y] = new Block(BlockType.None);
                    if (chunk.LowestEmptyBlockOffset > y) chunk.LowestEmptyBlockOffset = (byte)y;
                }
                else if (y > rockHeight) // dirt
                {
                    var valleyNoise = this.GenerateValleyNoise(worldPositionX, worldPositionZ, y);
                    BlockStorage.Blocks[offset + y] = new Block(valleyNoise > 0.2f ? BlockType.None : BlockType.Dirt);
                    if (y > chunk.HighestSolidBlockOffset) chunk.HighestSolidBlockOffset = (byte)y;
                }
                else // rock level
                {
                    BlockStorage.Blocks[offset + y] = new Block(BlockType.Rock);
                    if (y > chunk.HighestSolidBlockOffset) chunk.HighestSolidBlockOffset = (byte)y;
                }
            }

            // apply the biome generator on x-z column.
            this.BiomeGenerator.ApplyBiome(chunk, dirtHeight, offset + dirtHeight, worldPositionX + this.Seed, worldPositionZ);
        }
Exemple #10
0
        public override iTextSharp.text.IElement GeneratePdfElement()
        {
            SignaturePanelStyle style = (Manifest != null) ? Manifest.Styles.GetMergedFromConfiguration(Style) : Style;

            Phrase phrase = new Phrase();

            Chunk signature = new Chunk(Signature);
            signature.Style.Font.Apply(style.Font);
            phrase.Content.Add(signature);
            phrase.Content.Add(new NewLine());

            Separator separator = new Separator();
            separator.Style.BorderColor = style.BorderColor;
            separator.Style.Width = style.BorderWidth;
            phrase.Content.Add(separator);

            GenericIdentity identity = new GenericIdentity(User);

            AD.ActiveDirectory activeDirectory = new AD.ActiveDirectory();
            UserDescriptor adUser = activeDirectory.GetUser(identity.GetUserName());
            string fullName = adUser.DisplayName;

            phrase.Content.Add(new NewLine());
            phrase.Content.Add(new Chunk(String.Format("{0} ({1:MMMM dd, yyyy})", fullName, Date)));

            PdfPanel panel = new PdfPanel(phrase);
            panel.Style.BackgroundColor = style.BackgroundColor;
            panel.Style.BorderColor = style.BorderColor;
            panel.Style.Padding = style.Padding;
            panel.Style.BorderWidth = style.BorderWidth;
            panel.Style.Width = style.Width;

            return panel.GeneratePdfElement();
        }
Exemple #11
0
    public virtual void Decorate(Chunk chunk)
    {
        if (Decorations != null && Decorations.Length > 0)
        {
            for (int i = 0; i < Decorations.Length; i++)
            {
                for (int j = 0; j < Decorationscount[i]; j++)
                {
                    int x = DataBaseHandler.DataBase.random.Next(0, DataBaseHandler.ChunkSize);
                    int y = DataBaseHandler.DataBase.random.Next(0, DataBaseHandler.ChunkSize);

                    if (chunk.biomes[Mathf.RoundToInt((((float)DataBaseHandler.BiomeMapSize - (float)1) / (float)DataBaseHandler.ChunkSize) * y), Mathf.RoundToInt((((float)DataBaseHandler.BiomeMapSize - (float)1) / (float)DataBaseHandler.ChunkSize) * x)] == Type)
                    {
                        RaycastHit hit;
                        Physics.Raycast(
                            new Vector3(chunk.transform.position.x + x, -1, chunk.transform.position.z + y), Vector3.up,
                            out hit, (float)DataBaseHandler.ChunkSize * 2.5f, 1);
                        GameObject go = (GameObject)GameObject.Instantiate(Decorations[i]);
                        go.transform.parent = chunk.transform;
                        go.transform.localPosition = new Vector3(x, hit.point.y, y);
                        Vector3 rot = Random.rotation.eulerAngles;
                        go.transform.eulerAngles = new Vector3(0, DataBaseHandler.DataBase.random.Next(0, 360), 0);
                        go.AddComponent<TreeHandler>();
                    }
                }
            }
        }
    }
Exemple #12
0
 public override void ApplyBiome(Chunk chunk, int groundLevel, int groundOffset, int worldPositionX, int worldPositionZ)
 {
     for (int y = 0; y < SnowDepth; y++)
     {
         BlockStorage.Blocks[groundOffset + y].Type = BlockType.Snow;
     }
 }
 public Chunk GenerateChunk(Vector3 position)
 {
     var chunk = new Chunk(position);
     int y = 0;
     for (int i = 0; i < Layers.Count; i++)
     {
         int height = y + Layers[i].Height;
         while (y < height)
         {
             for (int x = 0; x < 16; x++)
             {
                 for (int z = 0; z < 16; z++)
                 {
                     chunk.SetBlock(new Vector3(x, y, z), Layers[i].Block);
                 }
             }
             y++;
         }
     }
     for (int i = 0; i < chunk.Biomes.Length; i++)
         chunk.Biomes[i] = (byte)Biome;
     // TESTING
     // Dig out a little to test sky light
     for (y = 3; y > 0; y--)
         chunk.SetBlock(new Vector3(8, y, 8), new AirBlock());
     for (int x = -5; x < 5; x++)
         for (int z = -5; z < 5; z++)
             for (y = 2; y > 0; y--)
                 chunk.SetBlock(new Vector3(8 + x, y, 8 + z), new AirBlock());
     // /TESTING
     return chunk;
 }
    /// <summary>
    /// Generate a chunk and return it. The terrain object remains unmodified.
    /// </summary>
    /// <param name="terrain">The terrain.</param>
    /// <param name="chunkIndex">The chunk index.</param>
    /// <returns>The chunk.</returns>
    public Chunk GenerateChunk(Terrain terrain, Vector2I chunkIndex)
    {
        Chunk chunk = new Chunk();

        // Calculate the position of the chunk in world coordinates
        var chunkPos = new Vector2I(chunkIndex.X * Chunk.SizeX, chunkIndex.Y * Chunk.SizeY);

        // Get the surface heights for this chunk
        int[] surfaceHeights = this.GenerateSurfaceHeights(chunkPos);

        // For now, fill the terrain with mud under the surface
        for (int x = 0; x < Chunk.SizeX; x++)
        {
            int surfaceHeight = surfaceHeights[x];
            if (surfaceHeight > 0)
            {
                for (int y = 0; y < surfaceHeight; y++)
                {
                    chunk[x, y] = new Block(BlockType.Dirt);
                }
            }
        }

        return chunk;
    }
        public TileMap(int width, int height, Texture texture)
        {
            Width = width;
            Height = height;

            var lastTile = texture == null ? ushort.MaxValue : (ushort)((texture.Size.X / GameOptions.TileSize) * (texture.Size.Y / GameOptions.TileSize) - 1);

            tiles = new Tile[width, height];

            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    tiles[x, y].Index = lastTile;
                    tiles[x, y].Solid = false;
                }
            }

            var chunkWidth = (width / GameOptions.TileChunkSize) + 1;
            var chunkHeight = (height / GameOptions.TileChunkSize) + 1;

            chunks = new Chunk[chunkWidth, chunkHeight];

            for (var y = 0; y < chunkHeight; y++)
            {
                for (var x = 0; x < chunkWidth; x++)
                {
                    chunks[x, y] = new Chunk(x, y, tiles, texture);
                }
            }
        }
    private void CreateDecorationAt(Chunk chunk, int blockX, int blockY, int blockZ, IRandom random)
    {
        int offsetX = blockX;
        int offsetY = blockY;
        int numberOfVerticalSegments = BlockSize.Z / 5;
        int diskZ = blockZ;
        int radius = 5;
        BlockType blockType = BlockType.Stone;
        for (int seg = 0; seg < numberOfVerticalSegments; seg++)
        {
            for (int disc = 0; disc < 5; disc++)
            {
                CreateDiskAt(offsetX, offsetY, diskZ, radius, blockType);
                diskZ++;
            }
            if (radius > 1)
            {
                radius--;
                if (radius == 1)
                {
                    blockType = BlockType.Dirt;
                }
            }
        }

        AddGameObjectDecorationToWorld("gray diamond", chunk, new Vector3(blockX + 0.5f, blockY + 0.5f, diskZ + 0.1f),
                                       new Vector3(0, -90, 0));
    }
Exemple #17
0
        protected virtual void GenerateBlocks(Chunk chunk, int worldPositionX, int worldPositionZ)
        {
            var rockHeight = this.GetRockHeight(worldPositionX, worldPositionZ);
            var dirtHeight = this.GetDirtHeight(worldPositionX, worldPositionZ, rockHeight);

            var offset = BlockStorage.BlockIndexByWorldPosition(worldPositionX, worldPositionZ);

            for (int y = Chunk.MaxHeightIndexInBlocks; y >= 0; y--)
            {
                if (y > dirtHeight) // air
                {
                    BlockStorage.Blocks[offset + y] = new Block(BlockType.None);
                }
                else if (y > rockHeight) // dirt level
                {
                    BlockStorage.Blocks[offset + y] = new Block(BlockType.Dirt);
                }
                else // rock level
                {
                    BlockStorage.Blocks[offset + y] = new Block(BlockType.Rock);
                }
            }

            // apply the biome generator on x-z column.
            this.BiomeGenerator.ApplyBiome(chunk, dirtHeight, offset + dirtHeight, worldPositionX, worldPositionZ);
        }
    public override bool DoPass(ref Chunk chunk, ref RenderTexture densityTexture)
    {
     
        int[] data = new int[1];
        data[0] = 0;
        indexCounterBuffer.SetData(data);
        computeShader.SetBuffer(0, "indexCounter", indexCounterBuffer);
        computeShader.SetTexture(0, "densityTexture", densityTexture);
        computeShader.SetBuffer(0, "case_to_numpolys", Helper.GetCaseToNumPolyBuffer());
        computeShader.SetBuffer(0, "edge_connect_list", Helper.GetTriangleConnectionTable());
        computeShader.SetBuffer(0, "triangleBuffer", chunk.triangleBuffer);

        float invVoxelDim = 1.0f / ((float)chunk.voxelDim);
        computeShader.SetFloat("invVoxelDim", invVoxelDim);
        computeShader.SetVector("wsChunkPosLL", chunk.wsPosLL);
        computeShader.SetVector("wsChunkDim", chunk.wsChunkDim);
        computeShader.SetInt("voxelDim", chunk.voxelDim);
        int N = chunk.voxelDim;
        computeShader.Dispatch(0, N / 4, N / 4, N / 4);

        indexCounterBuffer.GetData(data);
        int numTriangles = data[0];
        chunk.triangleCount = numTriangles;


        return true;
    }
    /// <summary>
    /// Identifies all sunlit blocks, then lights all surrounding blocks
    /// </summary>
    /// <param name="chunk"></param>
    public void LightChunk(Chunk chunk)
    {
        if (chunk.IsOnTheBorder)
        {
            return;
        }

        LightSunlitBlocksInChunk(chunk);

        byte sunlight = Sunlight();
        int chunkWorldX = chunk.ArrayX * m_WorldData.ChunkBlockWidth;
        int chunkWorldY = chunk.ArrayY * m_WorldData.ChunkBlockHeight;

        for (int x = 0; x < m_WorldData.ChunkBlockWidth; x++)
        {
            int blockX = chunkWorldX + x;
            for (int y = 0; y < m_WorldData.ChunkBlockHeight; y++)
            {
                int blockY = chunkWorldY + y;

                for (int z = m_WorldData.ChunkBlockDepth - 1; z >= 0; z--)
                {
                    Block block = chunk.GetBlock(x, y, z);
                    // Only light blocks that surround a sunlit block (for now)
                    if (block.Type == BlockType.Air && block.LightAmount == sunlight)
                    {
                        SetLightingAroundBlock(blockX, blockY, z, 1);
                    }
                }
            }
        }
    }
Exemple #20
0
    public virtual MeshData Blockdata(Chunk chunk, int x, int y, int z, MeshData meshData)
    {
        // Check if block on top has a solid down face
        if (!chunk.GetBlock(x, y + 1, z).IsSolid(Direction.down)) {
            meshData = FaceDataUp(chunk, x, y, z, meshData);
        }

        // Check if the block below has a solid up face
        if (!chunk.GetBlock(x, y - 1, z).IsSolid(Direction.up)) {
            meshData = FaceDataDown(chunk, x, y, z, meshData);
        }

        // Check if the block north has a solid south face
        if (!chunk.GetBlock(x, y, z + 1).IsSolid(Direction.south)) {
            meshData = FaceDataNorth(chunk, x, y, z, meshData);
        }

        // Check if the block south has a solid north face
        if (!chunk.GetBlock(x, y, z - 1).IsSolid(Direction.north)) {
            meshData = FaceDataSouth(chunk, x, y, z, meshData);
        }

        // Check if the block east has a solid west face
        if (!chunk.GetBlock(x + 1, y, z).IsSolid(Direction.west)) {
            meshData = FaceDataEast(chunk, x, y, z, meshData);
        }

        // Check if the block west has a solid east face
        if (!chunk.GetBlock(x - 1, y, z).IsSolid(Direction.east)) {
            meshData = FaceDataWest(chunk, x, y, z, meshData);
        }

        return meshData;
    }
		public void DrawVerticalLine(Chunk chunk, ChunkLayer layer, int top, int bottom, int x, int blockId)
		{
			for (var row = top; row <= bottom; row++)
			{
				chunk[layer, x, row] = blockId;
			}
		}
        /// <summary>
        /// Load a chunk into the terrain object.
        /// </summary>
        /// <param name="terrain">The terrain.</param>
        /// <param name="chunkIndex">The chunk index.</param>
        /// <returns>The chunk.</returns>
        public Chunk LoadChunk(VoxelTerrain terrain, Position chunkIndex)
        {
            // Deserialize or generate the chunk
            Chunk chunk;
            if (!this.serializer.TryDeserialiseChunk(chunkIndex, out chunk))
            {
                // Get the surface heights of the chunk
                float[] surfaceHeights;
                if (!terrain.SurfaceHeights.TryGetValue(chunkIndex.X, out surfaceHeights))
                {
                    surfaceHeights = this.voxelGenerator.GenerateSurfaceHeights(chunkIndex.X);
                    terrain.SurfaceHeights.Add(chunkIndex.X, surfaceHeights);
                }

                // The chunk doesn't yet exist, so generate a new one
                chunk = new Chunk();
                this.voxelGenerator.Generate(chunk.Voxels, surfaceHeights, chunkIndex);

                // Serialize the generated chunk
                this.serializer.SerialiseChunk(chunk, chunkIndex);
            }

            // Add the chunk to the terrain object
            terrain.Chunks.Add(chunkIndex, chunk);

            return chunk;
        }
Exemple #23
0
	public void ApplyChunkSettings(Chunk chunk, CubedObjectBehaviour parent) {
		this.chunk = chunk;
		renderer.materials = new Material[] { chunk.blockMaterial };
		
		var mesh = new Mesh();
		mesh.Clear();
	    mesh.vertices = chunk.meshData.RenderableVertices.ToArray();
	    mesh.triangles = chunk.meshData.RenderableTriangles.ToArray();
	    mesh.uv = chunk.meshData.RenderableUvs.ToArray();
	    mesh.RecalculateNormals();
		
		var meshFilter = GetComponent<MeshFilter>();
	    // sharedMesh is null during generation
	    // TODO: Fix this as the generator shows errors in the console when using mesh vs. sharedMesh
	    //mesh = (meshFilter.mesh if EditorApplication.isPlayingOrWillChangePlaymode else meshFilter.sharedMesh)
		if(Application.isPlaying) meshFilter.mesh = mesh;
		else meshFilter.sharedMesh = mesh;
		
		if(parent.colliderType == ColliderType.MeshColliderPerChunk) {
			var colliderMesh = new Mesh();
			colliderMesh.vertices = chunk.meshData.CollidableVertices.ToArray();
			colliderMesh.triangles = chunk.meshData.CollidableTriangles.ToArray();
			var meshCollider = GetComponent<MeshCollider>();
			if(colliderMesh != null) {
				if(meshCollider == null) meshCollider = gameObject.AddComponent<MeshCollider>();
			   	meshCollider.sharedMesh = colliderMesh;
			   	meshCollider.convex = false;
				meshCollider.enabled = true;
			}
			else {
				if(meshCollider != null) meshCollider.enabled = false;
			}
		}
		transform.localPosition = (chunk.gridPosition * parent.chunkDimensions).ToVector3() * parent.cubeSize;
	}
Exemple #24
0
        private void DoSkylighting(Chunk c)
        {
            int csx = (int)c.Size.X;
            int csz = (int)c.Size.Y;
            for (int _x = 0; _x < csx; _x++)
            {
                for (int _z = 0; _z < csz; _z++)
                {
                    int x = (int)(c.Position.X * csx) + _x;
                    int z = (int)(c.Position.Y * csz) + _z;
                    for (int y = 0; y < c.HeightMap[x, z]; y++)
                    {
                        byte currentSkyLight = c.SkyLight[x,y,z];

                        byte currentBlock = c.Blocks[x, y, z];

                        Block currentBlockInfo = OpenMinecraft.Blocks.Get(currentBlock);

                        // SUNLIGHT
                        currentSkyLight = (byte)(currentSkyLight - currentBlockInfo.Stop - 1);

                        if (currentSkyLight < 0) currentSkyLight = 0;
                        if (currentSkyLight > 15) currentSkyLight = 15;

                        c.SkyLight[x, y, z]=currentSkyLight;
                    }
                }
            }
            c.Save();
        }
Exemple #25
0
    protected virtual void GenerateTerrain(Chunk chunk, int x, int z)
    {
        int stoneHeight = LayerStoneBase(chunk.pos.x + x, chunk.pos.z + z);
        stoneHeight += LayerStoneNoise(chunk.pos.x + x, chunk.pos.z + z);

        int dirtHeight = stoneHeight + LayerDirt(chunk.pos.x + x, chunk.pos.z + z);
        //CreateTreeIfValid(x, z, chunk, dirtHeight);

        for (int y = 0; y < Config.Env.ChunkSize; y++)
        {

            if (y + chunk.pos.y <= stoneHeight)
            {
                SetBlock(chunk, "stone", new BlockPos(x, y, z));
            }
            else if (y + chunk.pos.y < dirtHeight)
            {
                SetBlock(chunk, "dirt", new BlockPos(x, y, z));
            }
            else if (y + chunk.pos.y == dirtHeight)
            {
                SetBlock(chunk, "grass", new BlockPos(x, y, z));
            }
            else if (y + chunk.pos.y == dirtHeight + 1 && GetNoise(x+chunk.pos.x, y + chunk.pos.y, z + chunk.pos.z, 10, 10, 1) > 5)
            {
                Block wildGrass = "wildgrass";
                wildGrass.data2 = (byte)(GetNoise(x + chunk.pos.x, y + chunk.pos.y, z + chunk.pos.z, 1, 155, 1)+100);

                SetBlock(chunk, wildGrass, new BlockPos(x, y, z));
            }

        }
    }
 public MeshGenerationJob(Chunk chunk, DensityProvider provider, Vector3 offset, Action<MeshProxy> callback)
 {
     this.provider = provider;
     this.offset = offset;
     this.callback = callback;
     this.chunk = chunk;
 }
Exemple #27
0
    protected virtual void GenerateTerrain(Chunk chunk, int x, int z)
    {
        //int stoneHeight = LayerStoneBase(chunk.pos.x + x, chunk.pos.z + z);
        //stoneHeight += LayerStoneNoise(chunk.pos.x + x, chunk.pos.z + z);
        int stoneHeight = stoneBaseHeight;
        int dirtHeight = stoneBaseHeight + LayerDirt(chunk.pos.x + x, chunk.pos.z + z);
        //CreateTreeIfValid(x, z, chunk, dirtHeight);

        for (int y = 0; y < Config.Env.ChunkSize; y++)
        {

            if (y + chunk.pos.y <= stoneHeight)
            {
                SetBlock(chunk, "stone", new BlockPos(x, y, z));
            }
            else if (y + chunk.pos.y < dirtHeight)
            {
                SetBlock(chunk, "dirt", new BlockPos(x, y, z));
            }
            else if (y + chunk.pos.y == dirtHeight)
            {
                SetBlock(chunk, "grass", new BlockPos(x, y, z));
            }

        }
    }
		public override Chunk Generate(IProgress<string> progress, int chunkX, int chunkY)
		{
			Reseed(chunkX, chunkY);

			var chunk = new Chunk(Width, Height);
			Fill(chunk, ChunkLayer.Background, _dirtId);
			Fill(chunk, ChunkLayer.Floor, _grassId);

			for (var x = 0; x < Width; x++)
			{
				for (var y = 0; y < Height; y++)
				{
					var value = SimplexNoise.Generate((chunkX * Width + x) / 256.0f, (chunkY * Height + y) / 256.0f);
					if (value < -0.5)
					{
						chunk[ChunkLayer.Floor, x, y] = _waterId;
						chunk[ChunkLayer.Background, x, y] = _waterId;
					}
					else if (value < -0.25)
					{
						chunk[ChunkLayer.Floor, x, y] = _sandId;
						chunk[ChunkLayer.Background, x, y] = _sandId;
					}
					else if (value > 0.5)
					{
						chunk[ChunkLayer.Blocking, x, y] = _stoneId;
						chunk[ChunkLayer.Background, x, y] = _dirtId;
					}
				}
			}

			chunk = GenerateBushes(progress, chunk);

			return chunk;
		}
Exemple #29
0
 public static Task<Result> GenerateSectionAsync(ILogger logger, Chunk chunk, Point center, SizeF scaleSize, ushort maxIterations)
 {
     return Task.Run(() =>
     {
         return GenerateSection(logger, chunk, center, scaleSize, maxIterations);
     });
 }
    // Update is called once per frame
    void Update()
    {
        if (mousehold) {
            if (!Input.GetMouseButton (0))
                mousehold = false;
        }
        if ((!mousehold) && Input.GetMouseButton (0)) {
            mousehold = true;
            if (Input.GetKey (KeyCode.LeftShift)) {
                depth = 3;
            } else
                depth = 2;

            //create a target where we are pointing
        //			Vector3 mouse = Input.mousePosition;
        //			mouse.z = depth - (Camera.main.transform.position.z)-1;
        //
        //			targetPosition = Camera.main.ScreenToWorldPoint (mouse);
        //			targetPosition.z = depth-1;

            hostChunk = world.GetChunk(pos.x,pos.y,pos.z);
        //			pos.x = pos.x - hostChunk.pos.x;
        //			pos.y = pos.y - hostChunk.pos.y;
        //			pos.z = pos.z - hostChunk.pos.z;

            update = true;
        }

        if (update)
        {
            update = false;
            UpdateCube();
        }
    }
Exemple #31
0
 /**
  * Adds a <CODE>Chunk</CODE> to the current text array.
  * @param chunk the text
  */
 public void AddText(Chunk chunk)
 {
     chunks.Add(new PdfChunk(chunk, null));
 }
Exemple #32
0
        private void FinalHojaCreditosNOMicro(Document document)
        {
            var letraBlanca = FontFactory.GetFont("Arial", 15);

            letraBlanca.SetColor(255, 255, 255);

            var TitulosLetra = FontFactory.GetFont("Arial", 15, iTextSharp.text.Font.BOLD);

            TitulosLetra.SetColor(248, 100, 26);

            var informacionFinancieraEgresos = new Paragraph("Información Financiera (Egresos):", TitulosLetra);


            var deduccionesSeguridadSocial      = new Chunk("Deducciones seguridad social: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var deduccionesSeguridadSocialValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.DeduccionesDeSeguridadSocial)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var otrasDeduccionesColilla      = new Chunk("otras deducciones de colilla: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var otrasDeduccionesColillaValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.OtrasDeduccionesColilla)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var totalDeducciones      = new Chunk("Total deducciones de colilla: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var totalDeduccionesValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.DeduccionesColilla)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var cuotasACancelar      = new Chunk("Cuotas a cancelar: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var cuotasACancelarValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.CuotasACancelar)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var estimacionCupoRotativo      = new Chunk("Estimación Cupo Rotativo: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var estimacionCupoRotativoValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.EstimacionCupoRotativo)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var valorCuotaLibranza      = new Chunk("Valor cuota libranza: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var valorCuotaLibranzaValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.ValorCuotaLibranza)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var cuotaCreditoCancelarNomina      = new Chunk("Cuota de crédito a cancelar por nómina: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var cuotaCreditoCancelarNominaValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.CuotasDeCreditoACancelarPorNomina)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var estimacionTarjetasCredito      = new Chunk("Estimación tarjetas de crédito: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var estimacionTarjetasCreditoValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.EstimacionTarjetasDeCredito)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var cuotaCentralesDeRiesgo      = new Chunk("Cuota centrales de riesgo: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var cuotaCentralesDeRiesgoValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.CuotaCentrales)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));


            var calificacionSolicitante = new Paragraph("Calificación Del Solicitante:", TitulosLetra);


            var score      = new Chunk("Score: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var scoreValor = new Chunk($"{string.Format("{0:#,0.0}", Cache.Score)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var calificacion      = new Chunk("Calificación: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var calificacionValor = new Chunk($"{Cache.Calificacion} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var afectacionColilla      = new Chunk("Afectación colilla: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var afectacionColillaValor = new Chunk($"{ Cache.AfectacionColilla.ToString("P2")} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var endeudamientoGlobal      = new Chunk("Endeudamiento global: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var endeudamientoGlobalValor = new Chunk($"{Cache.EndeudamientoGlobal.ToString("P2")} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var disponible      = new Chunk("Disponible: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var disponibleValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.Disponible)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var leyLibranza      = new Chunk("Ley de libranza: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var leyLibranzaValor = new Chunk($"{Cache.AplicaLeyLibranza} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var totalMoras      = new Chunk("Total moras: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var totalMorasValor = new Chunk($"{Cache.ComportamientoDePagos} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));


            var cumplimientoPoliticasTitulo = new Paragraph("Cumplimiento De Políticas:", TitulosLetra);
            var cumplimientoPoliticasValor  = new Chunk($"{Cache.CumplimientoDePoliticias} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));


            var criterioAnalistaTitulo = new Paragraph("Criterio del analista:", TitulosLetra);
            var criterioAnalistaValor  = new Chunk($"{Cache.CriterioDelAnalista} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));



            document.Add(informacionFinancieraEgresos);
            CrearEspacios(2, document);
            document.Add(deduccionesSeguridadSocial);
            document.Add(deduccionesSeguridadSocialValor);
            document.Add(otrasDeduccionesColilla);
            document.Add(otrasDeduccionesColillaValor);
            document.Add(totalDeducciones);
            document.Add(totalDeduccionesValor);
            CrearEspacios(1, document);
            document.Add(cuotasACancelar);
            document.Add(cuotasACancelarValor);
            document.Add(estimacionCupoRotativo);
            document.Add(estimacionCupoRotativoValor);
            CrearEspacios(1, document);
            document.Add(valorCuotaLibranza);
            document.Add(valorCuotaLibranzaValor);
            document.Add(cuotaCreditoCancelarNomina);
            document.Add(cuotaCreditoCancelarNominaValor);
            CrearEspacios(1, document);
            document.Add(estimacionTarjetasCredito);
            document.Add(estimacionTarjetasCreditoValor);
            document.Add(cuotaCentralesDeRiesgo);
            document.Add(cuotaCentralesDeRiesgoValor);
            CrearEspacios(2, document);

            document.Add(calificacionSolicitante);
            CrearEspacios(2, document);
            document.Add(score);
            document.Add(scoreValor);
            document.Add(calificacion);
            document.Add(calificacionValor);
            document.Add(afectacionColilla);
            document.Add(afectacionColillaValor);
            CrearEspacios(1, document);
            document.Add(endeudamientoGlobal);
            document.Add(endeudamientoGlobalValor);
            document.Add(disponible);
            document.Add(disponibleValor);
            document.Add(leyLibranza);
            document.Add(leyLibranzaValor);
            document.Add(totalMoras);
            document.Add(totalMorasValor);
            CrearEspacios(2, document);

            document.Add(cumplimientoPoliticasTitulo);
            CrearEspacios(2, document);
            document.Add(cumplimientoPoliticasValor);
            CrearEspacios(2, document);

            document.Add(criterioAnalistaTitulo);
            CrearEspacios(2, document);
            document.Add(criterioAnalistaValor);
            CrearEspacios(9, document);
        }
Exemple #33
0
        public void Exportar(DataGridView dataGridView1)
        {
            //Creating iTextSharp Table from the DataTable data


            PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);

            pdfTable.DefaultCell.Padding     = 3;
            pdfTable.WidthPercentage         = 100;
            pdfTable.HorizontalAlignment     = Element.ALIGN_CENTER;
            pdfTable.DefaultCell.BorderWidth = 1;


            //letras
            var letraBlanca = FontFactory.GetFont("Arial", 15);

            letraBlanca.SetColor(255, 255, 255);

            var TitulosLetra = FontFactory.GetFont("Arial", 15, iTextSharp.text.Font.BOLD);

            TitulosLetra.SetColor(248, 100, 26);


            //Añadir titulo del plan de pagos

            var Titulo = new Paragraph("ANÁLISIS DEL CRÉDITO", TitulosLetra);

            Titulo.Alignment = Element.ALIGN_CENTER;


            var informacionBasica = new Paragraph("Información Básica:", TitulosLetra);

            var planDePAgo = new Paragraph("Plan de pago:", TitulosLetra);


            var cedula      = new Chunk("Cédula: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var cedulaValor = new Chunk($"{string.Format("{0:#,0}", Convert.ToDouble(Cache.Cedula))}, ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var nombre      = new Chunk("Nombre: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var nombrevalor = new Chunk($"{Cache.Nombre} {Cache.Apellido}", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));



            var informacionCredito = new Paragraph("Información Del Crédito:", TitulosLetra);


            var monto      = new Chunk("Monto Crédito: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var montoValor = new Chunk($"{string.Format("{0:#,0}", Cache.Monto)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var plazo      = new Chunk("Plazo: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var plazoValor = new Chunk($"{string.Format("{0:#,0}", Convert.ToDouble(Cache.Plazo))} meses ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var tasa      = new Chunk("Tasa MV: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var tasaValor = new Chunk($"{string.Format("{0:#,0.00}", Convert.ToDouble(Cache.Tasa))} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var Cuota      = new Chunk("Cuota: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var cuotaValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.Cuota)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var periodicidad      = new Chunk("Periodicidad: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var periodicidadValor = new Chunk($"{Cache.Periodicidad} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var garantia      = new Chunk("Garantía: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var garantiaValor = new Chunk($"{Cache.Garantia} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var formaDePago      = new Chunk("Forma de pago: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var formaDePagoValor = new Chunk($"{Cache.FormaDePago} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var tipoDeCredito      = new Chunk("Tipo de Crédito: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var tipoDeCreditoValor = new Chunk($"{ValidarTipoDeCredito()} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));



            var informacionGeneral = new Paragraph("Información General:", TitulosLetra);


            var fechaNacimiento      = new Chunk("Fecha de nacimiento: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var fechaNacimientoValor = new Chunk($"{Cache.FechaDeNaciento} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var estadiCivil      = new Chunk("Estado civil: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var estadiCivilValor = new Chunk($"{Cache.EstadoCivil} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var profesion      = new Chunk("Profesión: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var profesionValor = new Chunk($"{Cache.Profesion} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var edad      = new Chunk("Edad: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var edadValor = new Chunk($"{Cache.Edad} años ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var cargo      = new Chunk("Cargo: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var cargoValor = new Chunk($"{Cache.Cargo} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var personasACargo      = new Chunk("Personas a cargo: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var personasACargoValor = new Chunk($"{Cache.PersonasAcargo} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var ocupacion      = new Chunk("Ocupación: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var ocupacionValor = new Chunk($"{Cache.Ocupacion} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var tipovivienda      = new Chunk("Tipo de vivienda: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var tipoViviendaValor = new Chunk($"{Cache.Vivienda} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));



            var informacionLaboral = new Paragraph("Información Laboral:", TitulosLetra);


            var empresa      = new Chunk("Empresa: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var empresaValor = new Chunk($"{Cache.Empresa} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var actividadEconomica      = new Chunk("Actividad económica: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var actividadEconomicaValor = new Chunk($"{Cache.ActividadEconomica} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var tipoDeContrato      = new Chunk("Tipo de contrato: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var tipoDeContratoValor = new Chunk($"{Cache.TipoDeContrato} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var antLaboral      = new Chunk("Ant. Laboral: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var antLaboralValor = new Chunk($"{Cache.AntLaboral} meses", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));



            var informacionFinancieraIngresos = new Paragraph("Información Financiera (Ingresos):", TitulosLetra);


            var ingresos      = new Chunk("Ingresos: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var ingresosValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.IngresoBasico)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var otrosIngresos      = new Chunk("Otros ingresos: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var otrosIngresosValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.OtrosIngresos)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));

            var totalIngresos      = new Chunk("Total ingresos: ", FontFactory.GetFont("Arial", 15, color: new BaseColor(77, 77, 77)));
            var totalIngresosValor = new Chunk($"{string.Format("{0:#,0.00}", Cache.TotalIngresos)} ", FontFactory.GetFont("Arial", 15, new BaseColor(0, 0, 0)));


            var nombreAnalista = new Paragraph($"Nombre del analista: {Cache.NombreAnalista}", TitulosLetra);


            ////////
            //////
            ///
            //Desde aquí debe cambiar en caso de que sea un crédito de microcrédito

            //codigo para todos los créditos menos para micro



            //Adding Header row
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, letraBlanca))
                {
                    HorizontalAlignment = Element.ALIGN_MIDDLE
                };

                cell.BackgroundColor = new BaseColor(248, 100, 26);
                pdfTable.AddCell(cell);
            }
            //Adding DataRow
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    pdfTable.AddCell((Convert.ToDouble(cell.Value)).ToString("N2"));
                }
            }
            //Exporting to PDF
            string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            try
            {
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
            }
            catch (Exception e)
            {
                using (formError = new FormError($"Error tipo: {e}"))
                {
                    formError.ShowDialog();
                }
            }


            using (FileStream stream = new FileStream(folderPath + "/" + Cache.Cedula + " " + Cache.Nombre + " " + Cache.Apellido + ".pdf", FileMode.Create))
            {
                Document document = new Document(PageSize.A2, 90f, 90f, 30f, 30f);
                PdfWriter.GetInstance(document, stream);
                document.Open();
                CrearEspacios(3, document);
                document.Add(Titulo);
                CrearEspacios(3, document);

                document.Add(informacionBasica);
                CrearEspacios(2, document);
                document.Add(cedula);
                document.Add(cedulaValor);
                document.Add(nombre);
                document.Add(nombrevalor);
                CrearEspacios(2, document);

                document.Add(informacionCredito);
                CrearEspacios(2, document);
                document.Add(monto);
                document.Add(montoValor);
                document.Add(plazo);
                document.Add(plazoValor);
                document.Add(tasa);
                document.Add(tasaValor);
                document.Add(Cuota);
                document.Add(cuotaValor);
                CrearEspacios(1, document);
                document.Add(periodicidad);
                document.Add(periodicidadValor);
                document.Add(garantia);
                document.Add(garantiaValor);
                document.Add(formaDePago);
                document.Add(formaDePagoValor);
                document.Add(tipoDeCredito);
                document.Add(tipoDeCreditoValor);
                CrearEspacios(2, document);

                document.Add(informacionGeneral);
                CrearEspacios(2, document);
                document.Add(fechaNacimiento);
                document.Add(fechaNacimientoValor);
                document.Add(estadiCivil);
                document.Add(estadiCivilValor);
                document.Add(profesion);
                document.Add(profesionValor);
                document.Add(edad);
                document.Add(edadValor);
                CrearEspacios(1, document);
                document.Add(cargo);
                document.Add(cargoValor);
                document.Add(personasACargo);
                document.Add(personasACargoValor);
                document.Add(ocupacion);
                document.Add(ocupacionValor);
                document.Add(tipovivienda);
                document.Add(tipoViviendaValor);
                CrearEspacios(2, document);

                document.Add(informacionLaboral);
                CrearEspacios(2, document);
                document.Add(empresa);
                document.Add(empresaValor);
                document.Add(actividadEconomica);
                document.Add(actividadEconomicaValor);
                document.Add(tipoDeContrato);
                document.Add(tipoDeContratoValor);
                document.Add(antLaboral);
                document.Add(antLaboralValor);
                CrearEspacios(2, document);

                document.Add(informacionFinancieraIngresos);
                CrearEspacios(2, document);
                document.Add(ingresos);
                document.Add(ingresosValor);
                document.Add(otrosIngresos);
                document.Add(otrosIngresosValor);
                document.Add(totalIngresos);
                document.Add(totalIngresosValor);
                CrearEspacios(2, document);

                //fin de hoja según el tipo de crédito
                if (Cache.TipoDeCredito != 4)
                {
                    FinalHojaCreditosNOMicro(document);
                }
                else
                {
                    FinalHojaCreditosMICRO(document);
                }

                CrearEspacios(3, document);
                document.Add(planDePAgo);
                CrearEspacios(2, document);
                document.Add(pdfTable);
                CrearEspacios(3, document);
                AplicarCodeudor(document);
                document.Add(nombreAnalista);
                document.Close();
                stream.Close();
            }
        }
Exemple #34
0
    public virtual Vector3 ScanForTileEntityInList(List <String> lstBlocks, List <String> lstContents)
    {
        // If there's no blocks to look for, don't do anything.
        if (lstBlocks.Count == 0)
        {
            return(Vector3.zero);
        }

        DisplayLog("Scanning For Tile Entities: " + string.Join(", ", lstBlocks.ToArray()));
        DisplayLog(" Contents: " + string.Join(", ", lstContents.ToArray()));
        List <Vector3> localLists = new List <Vector3>();


        // Otherwise, search for your new home.
        Vector3i blockPosition = this.theEntity.GetBlockPosition();
        int      num           = World.toChunkXZ(blockPosition.x);
        int      num2          = World.toChunkXZ(blockPosition.z);

        for (int i = -1; i < 2; i++)
        {
            for (int j = -1; j < 2; j++)
            {
                Chunk chunk = (Chunk)theEntity.world.GetChunkSync(num + j, num2 + i);
                if (chunk != null)
                {
                    // Grab all the Tile Entities in the chunk
                    DictionaryList <Vector3i, TileEntity> tileEntities = chunk.GetTileEntities();
                    for (int k = 0; k < tileEntities.list.Count; k++)
                    {
                        TileEntityLootContainer tileEntity = tileEntities.list[k] as TileEntityLootContainer;
                        if (tileEntity != null)
                        {
                            BlockValue block = theEntity.world.GetBlock(tileEntity.ToWorldPos());
                            DisplayLog(" Found Block: " + block.Block.GetBlockName());
                            // if its not a listed block, then keep searching.
                            if (!lstBlocks.Contains(block.Block.GetBlockName()))
                            {
                                continue;
                            }

                            DisplayLog(" Tile Entity is in my Filtered list: " + block.Block.GetBlockName());
                            if (lstContents.Count > 0)
                            {
                                DisplayLog(" My Content List is Empty. Searcing for regular food items.");
                                if (CheckContents(tileEntity, lstContents, "Food") != null)
                                {
                                    DisplayLog(" Box has food contents: " + tileEntities.ToString());
                                    localLists.Add(tileEntity.ToWorldPos().ToVector3());
                                }
                                else
                                {
                                    DisplayLog(" Empty Container: " + tileEntities.ToString());
                                }
                            }
                            else
                            {
                                localLists.Add(tileEntity.ToWorldPos().ToVector3());
                            }
                        }
                    }
                }
            }
        }

        // DisplayLog(" Local List: " + string.Join(", ", localLists.ToArray()));

        // Finds the closet block we matched with.
        Vector3 tMin = new Vector3();

        tMin = Vector3.zero;
        float   minDist    = Mathf.Infinity;
        Vector3 currentPos = this.theEntity.position;

        foreach (Vector3 block in localLists)
        {
            float dist = Vector3.Distance(block, currentPos);
            if (dist < minDist)
            {
                tMin    = block;
                minDist = dist;
            }
        }

        return(tMin);
    }
Exemple #35
0
 public override Chunk Process(Chunk chunk)
 {
     LightingService.LocalPropagate(chunk, chunk.BuildingContext.LightPropagationVoxels);
     return(chunk);
 }
Exemple #36
0
 public override bool CanDecode(Chunk chunk)
 {
     return(true);
 }
Exemple #37
0
 public EntityHuman(Chunk chunk, CompoundTag nbt) : base(chunk, nbt)
 {
 }
Exemple #38
0
 public MDDF(Chunk c) : base(c, c.Size)
 {
 }
Exemple #39
0
        public void CreatPdf()
        {
            string name = _firstName + " " + _lastName;

            _path = Path.Combine(Environment.CurrentDirectory, "ticket.pdf");

            FileStream file = File.Create(_path);
            //document
            Rectangle rectangle = new Rectangle(400, 250);
            Document  document  = new Document(rectangle);

            document.SetMargins(5f, 5f, 10f, 5f);
            PdfWriter writer = PdfWriter.GetInstance(document, file);

            try
            {
                document.AddAuthor("Event Company");
                document.AddKeywords("Event");
                document.AddTitle("The ticket for this person");

                document.Open();
                Font heading = FontFactory.GetFont("courier", 13);
                Font body    = FontFactory.GetFont("courier", 10);

                Paragraph p1 = new Paragraph("Dot Net CONFERENCE", heading);
                p1.Alignment = Element.ALIGN_CENTER;
                Paragraph p2 = new Paragraph(" ");

                Paragraph p3 = new Paragraph("VENUE", heading);
                p3.Alignment = Element.ALIGN_CENTER;
                Paragraph p4 = new Paragraph("12 Life Avenue, Black Street, Victoria Island, Lagos State", body);
                p4.Alignment = Element.ALIGN_CENTER;

                Paragraph p5 = new Paragraph("DATE", heading);
                p5.Alignment = Element.ALIGN_CENTER;
                Paragraph p6 = new Paragraph("20 October, 2019 at 1.00 pm CAT", body);
                p6.Alignment = Element.ALIGN_CENTER;

                Paragraph p7 = new Paragraph(" ");

                Paragraph p8 = new Paragraph("NAME", heading);
                p8.Alignment = Element.ALIGN_CENTER;
                Paragraph p9 = new Paragraph(name, body);
                p9.Alignment = Element.ALIGN_CENTER;

                Chunk chk1 = new Chunk("SEAT NUMBER: ", heading);
                Chunk chk2 = new Chunk(_seatNumber, body);

                Phrase phrase = new Phrase();
                phrase.Add(chk1);
                phrase.Add(chk2);

                Paragraph p10 = new Paragraph();
                p10.Add(phrase);
                p10.Alignment = Element.ALIGN_CENTER;

                Phrase[] phrasesArray = new Phrase[] { p1, p2, p3, p4, p5, p6, p7, p8, p9, p10 };
                for (int i = 0; i < phrasesArray.Length; i++)
                {
                    document.Add(phrasesArray[i]);
                }
            }
            catch (DocumentException documentException)
            {
                throw documentException;
            }
            catch (IOException ioException)
            {
                throw ioException;
            }
            finally
            {
                document.Close();
                writer.Close();
                file.Close();
            }
        }
Exemple #40
0
 protected override void DrawChunk(Chunk chunk)
 {
     HasDrawn = true;
 }
Exemple #41
0
 private static void GetMapColors(Chunk chunk, int count, int total, float elapsedTime)
 {
     chunk.GetMapColors();
 }
Exemple #42
0
 public MDDF(Chunk c, uint h) : base(c, h)
 {
 }
Exemple #43
0
        public void SaveChunks(Chunk[] chunks)
        {
            int width = 32;
            int depth = 32;

            Chunk chunk = chunks[0];
            int   rx    = chunk.X >> 5;
            int   rz    = chunk.Z >> 5;

            string filePath = Path.Combine(this.WorldPath, $@"region/r.{rx}.{rz}.mca");

            if (!File.Exists(filePath))
            {
                Directory.CreateDirectory(this.RegionPath);

                using (var regionFile = File.Open(filePath, FileMode.CreateNew))
                {
                    byte[] buffer = new byte[8192];
                    regionFile.Write(buffer, 0, buffer.Length);
                }
            }

            using (var regionFile = File.Open(filePath, FileMode.Open))
            {
                byte[] buffer = new byte[8192];
                regionFile.Read(buffer, 0, buffer.Length);

                for (int i = 0; i < chunks.Length; i++)
                {
                    chunk = chunks[i];
                    int xi = (chunk.X % width);
                    if (xi < 0)
                    {
                        xi += 32;
                    }
                    int zi = (chunk.Z % depth);
                    if (zi < 0)
                    {
                        zi += 32;
                    }
                    int tableOffset = (xi + zi * width) * 4;

                    regionFile.Seek(tableOffset, SeekOrigin.Begin);

                    byte[] offsetBuffer = new byte[4];
                    regionFile.Read(offsetBuffer, 0, 3);
                    Array.Reverse(offsetBuffer);
                    int  offset      = BitConverter.ToInt32(offsetBuffer, 0) << 4;
                    byte sectorCount = (byte)regionFile.ReadByte();

                    byte[] nbtBuf         = NBTIO.WriteZLIBFile(this.ChunkFormat.NBTSerialize(chunk));
                    int    nbtLength      = nbtBuf.Length;
                    byte   nbtSectorCount = (byte)Math.Ceiling(nbtLength / 4096d);

                    if (offset == 0 || sectorCount == 0 || nbtSectorCount > sectorCount)
                    {
                        regionFile.Seek(0, SeekOrigin.End);
                        offset = (int)((int)regionFile.Position & 0xfffffff0);

                        regionFile.Seek(tableOffset, SeekOrigin.Begin);

                        byte[] bytes = BitConverter.GetBytes(offset >> 4);
                        Array.Reverse(bytes);
                        regionFile.Write(bytes, 0, 3);
                        regionFile.WriteByte(nbtSectorCount);
                    }

                    byte[] lenghtBytes = BitConverter.GetBytes(nbtLength + 1);
                    Array.Reverse(lenghtBytes);

                    regionFile.Seek(offset, SeekOrigin.Begin);
                    regionFile.Write(lenghtBytes, 0, 4);
                    regionFile.WriteByte(0x02);

                    regionFile.Write(nbtBuf, 0, nbtBuf.Length);

                    int reminder;
                    Math.DivRem(nbtLength + 4, 4096, out reminder);

                    byte[] padding = new byte[4096 - reminder];
                    if (padding.Length > 0)
                    {
                        regionFile.Write(padding, 0, padding.Length);
                    }
                }
            }
        }
Exemple #44
0
        private Chunk GetOrCreate(int x, int z)
        {
            //Log.WriteInfo ($"Getting chunk {x},{z}");
            Chunk chunk  = null;
            bool  loaded = false;

            lock (mapChunks)
            {
                if (x > MaxChunkLimit || x < -MaxChunkLimit || z > MaxChunkLimit || z < -MaxChunkLimit)
                {
                    throw new ArgumentException("Chunk index exceeded");
                }
                int idx = x * MaxChunkLimit + z;
                if (mapChunks.ContainsKey(idx))
                {
                    return(mapChunks[idx].Chunk);
                }

                chunk = LoadChunk(new ChunkCoords(x, z));
                if (chunk != null)
                {
                    chunk.BuildHeightMap();
                    loaded = true;
                }

                // Create Chunk
                Log.WriteInfo($"Generating {x},{z}");
                var mapChunk    = new MapChunk();
                var chunkCoords = new ChunkCoords(x, z);
                if (!loaded)
                {
                    chunk = new Chunk(chunkCoords);
                }
                mapChunk.Chunk = chunk;
                mapChunks[idx] = mapChunk;

                if (x > MaxXChunk)
                {
                    MaxXChunk = x;
                }
                if (x < MinXChunk)
                {
                    MinXChunk = x;
                }
                if (z > MaxZChunk)
                {
                    MaxZChunk = z;
                }
                if (z < MinZChunk)
                {
                    MinZChunk = z;
                }

                if (!loaded)
                {
                    generator.Generate(chunk);
                    SaveChunk(chunk);
                }
                chunk.FinishedGeneration = true;
                Log.WriteInfo($"Chunk {chunk.ChunkCoords} generated");
            }
            return(chunk);
        }
Exemple #45
0
        public static IEnumerable <FileDiff> Parse(string input, string lineEnding = "\n")
        {
            var lines = StringHelper.SplitLines(input, lineEnding);

            if (!lines.Any())
            {
                return(Enumerable.Empty <FileDiff>());
            }

            var files  = new List <FileDiff>();
            var in_del = 0;
            var in_add = 0;

            Chunk    current = null;
            FileDiff file    = null;

            int oldStart, newStart;
            int oldLines, newLines;

            ParserAction start = (line, m) => {
                file = new FileDiff();
                files.Add(file);

                if (file.To == null && file.From == null)
                {
                    var fileNames = parseFile(line);

                    if (fileNames != null)
                    {
                        file.From = fileNames[0];
                        file.To   = fileNames[1];
                    }
                }
            };

            ParserAction restart = (line, m) => {
                if (file == null || file.Chunks.Count != 0)
                {
                    start(null, null);
                }
            };

            ParserAction new_file = (line, m) => {
                restart(null, null);
                file.Type = FileChangeType.Add;
                file.From = "/dev/null";
            };

            ParserAction deleted_file = (line, m) => {
                restart(null, null);
                file.Type = FileChangeType.Delete;
                file.To   = "/dev/null";
            };

            ParserAction index = (line, m) => {
                restart(null, null);
                file.Index = line.Split(' ').Skip(1);
            };

            ParserAction from_file = (line, m) => {
                restart(null, null);
                file.From = parseFileFallback(line);
            };

            ParserAction to_file = (line, m) => {
                restart(null, null);
                file.To = parseFileFallback(line);
            };

            ParserAction chunk = (line, match) => {
                in_del   = oldStart = int.Parse(match.Groups[1].Value);
                oldLines = match.Groups[2].Success ? int.Parse(match.Groups[2].Value) : 0;
                in_add   = newStart = int.Parse(match.Groups[3].Value);
                newLines = match.Groups[4].Success ? int.Parse(match.Groups[4].Value) : 0;
                ChunkRangeInfo rangeInfo = new ChunkRangeInfo(
                    new ChunkRange(oldStart, oldLines),
                    new ChunkRange(newStart, newLines)
                    );

                current = new Chunk(line, rangeInfo);
                file.Chunks.Add(current);
            };

            ParserAction del = (line, match) => {
                string content = DiffLineHelper.GetContent(line);
                current.Changes.Add(new LineDiff(type: LineChangeType.Delete, index: in_del++, content: content));
                file.Deletions++;
            };

            ParserAction add = (line, m) => {
                string content = DiffLineHelper.GetContent(line);
                current.Changes.Add(new LineDiff(type: LineChangeType.Add, index: in_add++, content: content));
                file.Additions++;
            };

            const string noeol = "\\ No newline at end of file";

            Action <string> normal = line => {
                if (file == null)
                {
                    return;
                }

                string content = DiffLineHelper.GetContent(line);
                current.Changes.Add(new LineDiff(
                                        oldIndex: line == noeol ? 0 : in_del++,
                                        newIndex: line == noeol ? 0 : in_add++,
                                        content: content));
            };

            var schema = new Dictionary <Regex, ParserAction>
            {
                { new Regex(@"^diff\s"), start },
                { new Regex(@"^new file mode \d+$"), new_file },
                { new Regex(@"^deleted file mode \d+$"), deleted_file },
                { new Regex(@"^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$"), index },
                { new Regex(@"^---\s"), from_file },
                { new Regex(@"^\+\+\+\s"), to_file },
                { new Regex(@"^@@\s+\-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@"), chunk },
                { new Regex(@"^-"), del },
                { new Regex(@"^\+"), add }
            };

            Func <string, bool> parse = line => {
                foreach (var p in schema)
                {
                    var m = p.Key.Match(line);
                    if (m.Success)
                    {
                        p.Value(line, m);
                        return(true);
                    }
                }

                return(false);
            };

            foreach (var line in lines)
            {
                if (!parse(line))
                {
                    normal(line);
                }
            }

            return(files);
        }
Exemple #46
0
        /**
         * Constructs a <CODE>PdfChunk</CODE>-object.
         *
         * @param chunk the original <CODE>Chunk</CODE>-object
         * @param action the <CODE>PdfAction</CODE> if the <CODE>Chunk</CODE> comes from an <CODE>Anchor</CODE>
         */

        internal PdfChunk(Chunk chunk, PdfAction action)
        {
            thisChunk[0] = this;
            value        = chunk.Content;

            Font  f    = chunk.Font;
            float size = f.Size;

            if (size == iTextSharp.text.Font.UNDEFINED)
            {
                size = 12;
            }
            baseFont = f.BaseFont;
            BaseFont bf    = f.BaseFont;
            int      style = f.Style;

            if (style == iTextSharp.text.Font.UNDEFINED)
            {
                style = iTextSharp.text.Font.NORMAL;
            }
            if (baseFont == null)
            {
                // translation of the font-family to a PDF font-family
                baseFont = f.GetCalculatedBaseFont(false);
            }
            else
            {
                // bold simulation
                if ((style & iTextSharp.text.Font.BOLD) != 0)
                {
                    attributes[Chunk.TEXTRENDERMODE] = new Object[] { PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, size / 30f, null }
                }
                ;
                // italic simulation
                if ((style & iTextSharp.text.Font.ITALIC) != 0)
                {
                    attributes[Chunk.SKEW] = new float[] { 0, ITALIC_ANGLE }
                }
                ;
            }
            font = new PdfFont(baseFont, size);
            // other style possibilities
            Hashtable attr = chunk.Attributes;

            if (attr != null)
            {
                foreach (DictionaryEntry entry in attr)
                {
                    string name = (string)entry.Key;
                    if (keysAttributes.ContainsKey(name))
                    {
                        attributes[name] = entry.Value;
                    }
                    else if (keysNoStroke.ContainsKey(name))
                    {
                        noStroke[name] = entry.Value;
                    }
                }
                if ("".Equals(attr[Chunk.GENERICTAG]))
                {
                    attributes[Chunk.GENERICTAG] = chunk.Content;
                }
            }
            if (f.IsUnderlined())
            {
                Object[]   obj    = { null, new float[] { 0, 1f / 15, 0, -1f / 3, 0 } };
                Object[][] unders = Utilities.AddToArray((Object[][])attributes[Chunk.UNDERLINE], obj);
                attributes[Chunk.UNDERLINE] = unders;
            }
            if (f.IsStrikethru())
            {
                Object[]   obj    = { null, new float[] { 0, 1f / 15, 0, 1f / 3, 0 } };
                Object[][] unders = Utilities.AddToArray((Object[][])attributes[Chunk.UNDERLINE], obj);
                attributes[Chunk.UNDERLINE] = unders;
            }
            if (action != null)
            {
                attributes[Chunk.ACTION] = action;
            }
            // the color can't be stored in a PdfFont
            noStroke[Chunk.COLOR]    = f.Color;
            noStroke[Chunk.ENCODING] = font.Font.Encoding;
            Object[] obj2 = (Object[])attributes[Chunk.IMAGE];
            if (obj2 == null)
            {
                image = null;
            }
            else
            {
                attributes.Remove(Chunk.HSCALE); // images are scaled in other ways
                image         = (Image)obj2[0];
                offsetX       = ((float)obj2[1]);
                offsetY       = ((float)obj2[2]);
                changeLeading = (bool)obj2[3];
            }
            font.Image = image;
            object hs = attributes[Chunk.HSCALE];

            if (hs != null)
            {
                font.HorizontalScaling = (float)hs;
            }
            encoding       = font.Font.Encoding;
            splitCharacter = (ISplitCharacter)noStroke[Chunk.SPLITCHARACTER];
            if (splitCharacter == null)
            {
                splitCharacter = DefaultSplitCharacter.DEFAULT;
            }
        }
Exemple #47
0
        public UkmailLabel(string Ordernum, string Tracknum, string SenderAdress, double Weight, string ShippingDate, int totalParcel)
        {
            try
            {
                Code128B co128    = new Code128B();
                Document document = new Document(PageSize.A4);
                document.SetPageSize(new Rectangle(460, 320));
                co128.ValueFont = new System.Drawing.Font("Calibri", 20);
                System.Drawing.Bitmap imgTemp = co128.GetCodeImage(Tracknum, Code128B.Encode.Code128A);
                iTextSharp.text.Image img     = iTextSharp.text.Image.GetInstance((System.Drawing.Image)imgTemp, iTextSharp.text.BaseColor.WHITE);
                img.ScaleAbsoluteHeight(70);
                img.ScaleAbsoluteWidth(240);
                System.Drawing.Bitmap imgTemp1 = co128.GetCodeImage(Ordernum, Code128B.Encode.Code128A);
                iTextSharp.text.Image img1     = iTextSharp.text.Image.GetInstance((System.Drawing.Image)imgTemp1, iTextSharp.text.BaseColor.WHITE);
                img1.ScaleAbsoluteWidth(163);

                string     filename = "\\views\\pdf\\" + Ordernum + "2.pdf";
                FileStream fs       = new FileStream(AppDomain.CurrentDomain.BaseDirectory + filename, FileMode.Create);
                PdfWriter  writer   = PdfWriter.GetInstance(document, fs);
                document.SetMargins(10, 10, 2, 2);
                document.Open();
                PdfPTable table = new PdfPTable(1);
                table.WidthPercentage = 100;
                table.TotalWidth      = 1200;
                PdfPCell cell;
                BaseFont baseFT1 = BaseFont.CreateFont("C:/WINDOWS/Fonts/Helvetica.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseFont baseFT  = BaseFont.CreateFont("C:/WINDOWS/Fonts/Helvetica Bold.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                for (int i = 0; i < totalParcel; i++)
                {
                    document.NewPage();
                    PdfPTable table1 = new PdfPTable(4);
                    PdfPTable table2 = new PdfPTable(1);
                    cell = new PdfPCell(new Phrase("www.ukmail.com", new Font(baseFT1, 8)));
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.BorderWidthLeft     = 0;
                    cell.BorderWidthRight    = 0;
                    cell.BorderWidthTop      = 0;
                    cell.BorderWidthBottom   = 0;
                    table2.AddCell(cell);
                    Phrase ph = new Phrase();
                    Chunk  chunkCollection = new Chunk("Domestic Collection\r\nLIVE OPSYS\r\nLabel Produces:\r\n" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "\r\n \r\n ", new Font(baseFT, 10));
                    ph.Add(chunkCollection);
                    cell = new PdfPCell(ph);
                    cell.BorderWidthLeft     = 0;
                    cell.BorderWidthRight    = 0;
                    cell.BorderWidthTop      = 0;
                    cell.BorderWidthBottom   = 0;
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    table2.AddCell(cell);
                    cell = new PdfPCell(table2);
                    cell.BorderWidthLeft   = 0;
                    cell.BorderWidthRight  = 0;
                    cell.BorderWidthTop    = 0;
                    cell.BorderWidthBottom = 0;
                    cell.Colspan           = 1;
                    table1.AddCell(cell);
                    cell = new PdfPCell(img);
                    cell.BorderWidthLeft     = 0;
                    cell.BorderWidthRight    = 0;
                    cell.BorderWidthTop      = 0;
                    cell.BorderWidthBottom   = 0;
                    cell.Colspan             = 3;
                    cell.PaddingTop          = 10;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table1.AddCell(cell);
                    PdfPTable table3   = new PdfPTable(5);
                    Phrase    chunkFAO = new Phrase("FAO:Customer Import\r\nETAO LTD\r\nC/O ACCESS SELF STORAGE,OFFIC\r\nHARBORNE LANE SELLY OAK\r\nBIRMINGHAM", new Font(baseFT, 10));
                    cell = new PdfPCell(chunkFAO);
                    cell.BorderWidthLeft     = 0;
                    cell.BorderWidthRight    = 0;
                    cell.BorderWidthTop      = 0;
                    cell.BorderWidthBottom   = 0;
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.Colspan             = 2;

                    table3.AddCell(cell);
                    Phrase chunkConsignment = new Phrase("Consignment NO:    " + Tracknum + "\r\nWeight:                      " + Weight.ToString() + " Kg\r\nParcel:                       " + (i + 1).ToString() + " of " + totalParcel.ToString() + "\r\nTelephone:                0121 448 6510\r\nReference 1:\r\nnReference 2:\r\nCollection Driver:\r\nCollection Address:  " + SenderAdress, new Font(baseFT, 10));
                    cell = new PdfPCell(chunkConsignment);
                    cell.BorderWidthLeft     = 0;
                    cell.BorderWidthRight    = 0;
                    cell.BorderWidthTop      = 0;
                    cell.BorderWidthBottom   = 0;
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.Colspan             = 3;
                    table3.AddCell(cell);
                    //table.AddCell(table3);
                    PdfPTable table4 = new PdfPTable(5);
                    PdfPTable table5 = new PdfPTable(1);
                    Phrase    phrase = new Phrase();
                    Chunk     chk1   = new Chunk("B29 6SN\r\n", new Font(baseFT, 14));
                    Chunk     chk2   = new Chunk("Special Instructions\r\n \r\n", new Font(baseFT1, 8));
                    Chunk     chk3   = new Chunk(" \r\n" + Ordernum, new Font(baseFT1, 8));
                    Chunk     chk4   = new Chunk("\r\nETAO LTD", new Font(baseFT, 8));
                    phrase.Add(chk1);
                    phrase.Add(chk2);
                    cell = new PdfPCell(phrase);
                    cell.BorderWidthLeft   = 0;
                    cell.BorderWidthRight  = 0;
                    cell.BorderWidthTop    = 0;
                    cell.BorderWidthBottom = 0;
                    cell.Colspan           = 1;
                    table5.AddCell(cell);
                    cell = new PdfPCell(img1);
                    cell.BorderWidthLeft   = 0;
                    cell.BorderWidthRight  = 0;
                    cell.BorderWidthTop    = 0;
                    cell.BorderWidthBottom = 0;
                    cell.Colspan           = 1;
                    table5.AddCell(cell);
                    Phrase phrase1 = new Phrase();
                    phrase1.Add(chk3);
                    phrase1.Add(chk4);
                    cell = new PdfPCell(phrase1);
                    cell.BorderWidthLeft   = 0;
                    cell.BorderWidthRight  = 0;
                    cell.BorderWidthTop    = 0;
                    cell.BorderWidthBottom = 0;
                    cell.Colspan           = 1;
                    table5.AddCell(cell);
                    cell = new PdfPCell(table5);
                    cell.BorderWidthLeft     = 0;
                    cell.BorderWidthRight    = 0;
                    cell.BorderWidthTop      = 0;
                    cell.BorderWidthBottom   = 0;
                    cell.Colspan             = 2;
                    cell.PaddingTop          = 5;
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    table4.AddCell(cell);

                    Phrase phraseHome = new Phrase("HomeService           " + DateTime.Parse(ShippingDate).ToString("dd/MM/yyyy") + "\r\nNextDay\r\n \r\n \r\nBirmingham", new Font(baseFT, 17));
                    cell = new PdfPCell(phraseHome);
                    cell.BorderWidthLeft     = 0;
                    cell.BorderWidthRight    = 0;
                    cell.BorderWidthTop      = 0;
                    cell.BorderWidthBottom   = 0;
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.PaddingTop          = 5;
                    cell.Colspan             = 3;
                    cell.PaddingLeft         = 10;
                    table4.AddCell(cell);


                    cell = new PdfPCell(table1);
                    cell.BorderWidthLeft   = 0;
                    cell.BorderWidthRight  = 0;
                    cell.BorderWidthTop    = 0;
                    cell.BorderWidthBottom = 0;
                    cell.Colspan           = 1;
                    table.AddCell(cell);

                    cell = new PdfPCell(table3);
                    cell.BorderWidthLeft   = 0;
                    cell.BorderWidthRight  = 0;
                    cell.BorderWidthTop    = 0;
                    cell.BorderWidthBottom = 0;
                    cell.Colspan           = 1;
                    cell.FixedHeight       = 100;
                    table.AddCell(cell);
                    cell = new PdfPCell(table4);
                    cell.BorderWidthLeft   = 0;
                    cell.BorderWidthRight  = 0;
                    cell.BorderWidthTop    = 0;
                    cell.BorderWidthBottom = 0;
                    cell.Colspan           = 1;
                    table.AddCell(cell);
                    document.Add(table);
                }
                document.Close();
                fs.Close();
            }
            catch (DocumentException de)
            {
            }
            catch (IOException ioe)
            {
            }
        }
Exemple #48
0
        public void SetChunk(Chunk chunk)
        {
            Tuple <int, int> pos = new Tuple <int, int>(chunk.X, chunk.Z);

            this._chunks[pos] = chunk;
        }
        private void btn_Genera_Click(object sender, EventArgs e)
        {
            try
            {
                if (TuplaPDF[0] == null)
                {
                    MessageBox.Show("Empleado aun no seleccionado"); return;
                }
                Document  doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("../../../Reporte-Empleado.pdf", FileMode.Create));
                doc.Open();
                //codigo para agregar bordes de pagina al pdf
                var content        = wri.DirectContent;
                var pageBorderRect = new iTextSharp.text.Rectangle(doc.PageSize);

                pageBorderRect.Left   += doc.LeftMargin;
                pageBorderRect.Right  -= doc.RightMargin;
                pageBorderRect.Top    -= doc.TopMargin;
                pageBorderRect.Bottom += doc.BottomMargin;

                content.SetColorStroke(BaseColor.BLACK);
                content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height + 30);
                content.Stroke();

                //Para agregar imagen
                iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("../../../logo.jpg");
                PNG.ScalePercent(25f);
                //para posicion
                //PNG.SetAbsolutePosition(doc.PageSize.Width - 36f - 40f, doc.PageSize.Height - 36f - 50f);
                PNG.SetAbsolutePosition(171, 700);
                //para agregar un borde a la imagen
                PNG.Border      = iTextSharp.text.Rectangle.BOX;
                PNG.BorderColor = iTextSharp.text.BaseColor.BLACK;
                PNG.BorderWidth = 5f;
                doc.Add(PNG);


                //write some content

                Chunk     chunk = new Chunk("" + TuplaPDF[1] + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                Phrase    ph    = new Phrase("\n\r \n\r \n\r Nombre : ");
                Paragraph p     = new Paragraph(ph);
                p.Alignment = Element.ALIGN_LEFT;
                // p.SpacingBefore = spaceBefore;
                p.IndentationLeft = 120;
                p.Add((new Chunk(chunk)));//agregamos el nombre con linea
                //se agrega direccion
                ph = new Phrase("\t      Dirección : ");
                p.Add(ph);
                chunk = new Chunk("" + TuplaPDF[5] + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));
                //se agrega fecha nacimiento
                ph = new Phrase("\n\r Fecha de nacimiento : ");
                p.Add(ph);
                chunk = new Chunk("" + TuplaPDF[6].Substring(0, 10) + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));
                //se agrega telefono
                ph = new Phrase("\t      Telefono : ");
                p.Add(ph);
                chunk = new Chunk("" + TuplaPDF[4] + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));
                //se agrega Genero
                ph = new Phrase("\n\r Género : ");
                p.Add(ph);
                string genero = TuplaPDF[7] == "F" ? "Femenino" : "Masculino";
                chunk = new Chunk("" + genero + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));
                //se agrega Hora entrada
                ph = new Phrase("\n\r Hora entrada : ");
                p.Add(ph);
                chunk = new Chunk("" + TuplaPDF[8] + "am" + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));
                //se agrega hora salida
                ph = new Phrase("\t      Hora salida : ");
                p.Add(ph);
                chunk = new Chunk("" + TuplaPDF[9] + "pm" + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));
                //se agrega Sucursal donde trabaja
                ph = new Phrase("\n\r Sucursal : ");
                p.Add(ph);
                chunk = new Chunk("" + TuplaPDF[10] + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));
                //se agrega Sueldo
                ph = new Phrase("\n\r Sueldo : ");
                p.Add(ph);
                chunk = new Chunk("" + TuplaPDF[2] + " pesos" + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                p.Add((new Chunk(chunk)));


                doc.Add(p);


                /*Phrase ph = new Phrase("\n\r \n\r \n\r Nombre : " + TuplaPDF[1] + " Dirección : " + TuplaPDF[5] + "");
                 * Paragraph p = new Paragraph(ph);
                 * p.Alignment = Element.ALIGN_LEFT;
                 * // p.SpacingBefore = spaceBefore;
                 * p.IndentationLeft = 100;
                 * doc.Add(p);
                 * ph = new Phrase("\n\r \n\r \n\r Nombre : " + TuplaPDF[1] + " Dirección : " + TuplaPDF[5] + "");
                 * p = new Paragraph(ph);
                 * p.Alignment = Element.ALIGN_LEFT;
                 * // p.SpacingBefore = spaceBefore;
                 * p.IndentationLeft = 100;
                 * doc.Add(p);
                 *
                 */

                /*
                 * //Para crear una lista
                 * List list = new List(List.UNORDERED);
                 * list.Add(new ListItem("One"));
                 * list.Add("two");
                 * list.Add("two");
                 * list.Add("two");
                 * list.Add("two");
                 * list.Add(new ListItem("One"));
                 * doc.Add(list);
                 * */
                /*
                 * //para crear tabla en el pdf
                 *
                 * PdfPTable table = new PdfPTable(3);//el 3 es el numero de columnas
                 * //para header
                 * PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns", new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 8F, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.YELLOW)));
                 * cell.Colspan = 3;
                 * cell.HorizontalAlignment = 1;//0 left , 1 center , 2right
                 * table.AddCell(cell);
                 *
                 * table.AddCell("Col1 row1");
                 * table.AddCell("Col2 row1");
                 * table.AddCell("Col3 row1");
                 *
                 * table.AddCell("Col1 row2");
                 * table.AddCell("Col2 row2");
                 * table.AddCell("Col3 row2");
                 *
                 * doc.Add(table);
                 */
                /*
                 #region codigo para pasar datos del datagrid a pdf
                 * //codigo para pasar a una tabla la informacion del datagridview
                 * PdfPTable table = new PdfPTable(dataGridViewEmpleados.Columns.Count);
                 *
                 * //add the headers from the DGV to the table
                 * for (int j = 0; j < dataGridViewEmpleados.Columns.Count; j++)
                 * {
                 *  table.AddCell(new Phrase(dataGridViewEmpleados.Columns[j].HeaderText));
                 * }
                 *
                 * //flag the first row as a header
                 * table.HeaderRows = 1;
                 *
                 * //Add the actual rows from the DGV to the table
                 * for (int i = 0; i < dataGridViewEmpleados.Rows.Count; i++)
                 * {
                 *  for (int k = 0; k < dataGridViewEmpleados.Columns.Count; k++)
                 *  {
                 *      if (dataGridViewEmpleados[k, i].Value != null)
                 *      {
                 *          table.AddCell(new Phrase(dataGridViewEmpleados[k, i].Value.ToString()));
                 *      }
                 *  }
                 * }
                 *
                 * doc.Add(table);
                 #endregion*/
                doc.Close();
                System.Diagnostics.Process.Start("..\\..\\..\\Reporte-Empleado.pdf");
                //  MessageBox.Show("Reporte Creado!!!");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #50
0
        public void miseEnForm(string typeDoc)
        {
            string   cheminDocFinaux  = ConfigurationManager.AppSettings["CheminDocFinaux"].ToString();
            string   cheminRessources = ConfigurationManager.AppSettings["CheminRessources"].ToString();
            string   chemin           = cheminDocFinaux + "\\DocFinaux\\DEVIS\\DEVIS_" + nomDoc + "_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".pdf";
            Document nouveauDocument  = new Document(PageSize.A4, 20, 20, 12, 20);

            PdfWriter.GetInstance(nouveauDocument, new FileStream(chemin, FileMode.Create));     //Stockage du document
            nouveauDocument.Open();
            Image image4 = Image.GetInstance(ConfigurationManager.AppSettings["CheminPatternTot"]);

            image4.Alignment = Image.UNDERLYING;
            image4.SetAbsolutePosition(385, 70);
            //----------------------------------------------------------------------------------------------------Filligrane-----------------------------------------------
            Image image5 = Image.GetInstance(ConfigurationManager.AppSettings["CheminFilligraneDevis"]);

            image5.Alignment = Image.UNDERLYING;
            image5.SetAbsolutePosition(200, 250);
            nouveauDocument.Add(image5);
            //----------------------------------------
            //Constitution document PDF
            //----------------------------------------
            PdfPTable tableau = new PdfPTable(2);

            tableau.TotalWidth  = 550;
            tableau.LockedWidth = true;


            Image image6 = Image.GetInstance(ConfigurationManager.AppSettings["CheminLogoABCRDevis"]);

            image6.ScaleAbsolute(PageSize.A4);
            image6.ScaleToFit(175, 180);
            image6.SetAbsolutePosition(13, 715);
            nouveauDocument.Add(image6);

            Paragraph pLogo = new Paragraph();

            //Image image = Image.GetInstance(ConfigurationManager.AppSettings["CheminLogoABCRDevis"]);
            // pLogo.Add(image);
            //Encadré photo
            pLogo.Add(new Phrase(""));
            PdfPCell celulleHauteGauche = new PdfPCell(pLogo);

            celulleHauteGauche.Border = PdfPCell.NO_BORDER;
            tableau.AddCell(celulleHauteGauche);                                                         //Encadré info devis


            Paragraph pDoc   = new Paragraph();
            Image     image2 = Image.GetInstance(ConfigurationManager.AppSettings["CheminPatternHautDroiteDevis"]);

            image2.Alignment = Image.UNDERLYING;
            image2.SetAbsolutePosition(335, 740);
            nouveauDocument.Add(image2);
            pDoc.Alignment = Element.ALIGN_RIGHT;
            pDoc.Add(new Phrase("Devis n° " + donneeBody["Bon_numero1"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
            pDoc.Add(new Phrase("Date : " + donneeBody["Bon_datrcl1"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8)));
            pDoc.Add(new Phrase("Référence client : " + donneeBody["Bon_rcl1"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.RED)));
            pDoc.Add(new Phrase("Code client: " + donneEntete["Client_code"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8)));
            pDoc.Add(new Phrase(donneEntete["Tiers_tel"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8)));
            pDoc.Add(new Phrase(donneEntete["Tiers_fax"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8)));
            pDoc.Add(new Phrase(donneEntete["Tiers_adf5"], FontFactory.GetFont(FontFactory.HELVETICA, 8)));
            PdfPCell celulleHauteDroite = new PdfPCell(pDoc);

            celulleHauteDroite.Border = PdfPCell.NO_BORDER;
            celulleHauteDroite.HorizontalAlignment = Element.ALIGN_CENTER;
            tableau.AddCell(celulleHauteDroite);                                                                                        //Encadré "ABCR"
            Paragraph p = new Paragraph();

            p.Add(new Phrase(donneEntete["Adresse_interne_2"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
            p.Add(new Phrase(donneEntete["Adresse_interne_3"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
            p.Add(new Phrase(donneEntete["Adresse_interne_4"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.BOLD)));
            p.Add(new Phrase(donneEntete["Adresse_interne_5"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.BOLD)));
            p.Add(new Phrase(donneEntete["Adresse_interne_6"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.BOLD)));
            p.Add(new Phrase(donneEntete["Adresse_interne_7"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 9, Font.BOLD)));
            p.Add(new Phrase(donneEntete["Adresse_interne_8"] + "\n" + "\n" + "\n" + "\n" + "\n ", FontFactory.GetFont(FontFactory.HELVETICA, 9, Font.BOLD)));
            PdfPCell celluleBasGauche = new PdfPCell(p);

            celluleBasGauche.Border = PdfPCell.NO_BORDER;
            tableau.AddCell(celluleBasGauche);                                                                                        //Encadré client
            Paragraph pClient = new Paragraph();

            if (donneEntete["Tiers_adl1"] == "")
            {
                pClient.Add(new Phrase("\n" + "\n" + donneEntete["Tiers_adf1"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adf2"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adf3"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adf4"] + "\n" + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adfcp"] + "  " + donneEntete["Tiers_adf6"], FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
            }
            else
            {
                pClient.Add(new Phrase("\n" /*+"\n"*/ + donneEntete["Tiers_adl1"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adl2"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adl3"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adl4"] + "\n" + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
                pClient.Add(new Phrase(donneEntete["Tiers_adlcp"] + "  " + donneEntete["Tiers_adl6"], FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
            }
            PdfPCell celluleBasDroite = new PdfPCell(pClient);

            celluleBasDroite.Border = PdfPCell.NO_BORDER;
            tableau.AddCell(celluleBasDroite);
            nouveauDocument.Add(tableau);                                                                                                               //Dessus tableau
            Paragraph pRécap  = new Paragraph();
            Chunk     contact = null;

            contact = new Chunk("Votre contact : " + donneEntete["Bon_vendeur_lib"] + "\n     " + donneEntete["Duplicata"], FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.ITALIC));//FontFactory pour changer la police
            Chunk delai       = new Chunk("Livraison : " + donneEntete["Tiers_adf1"] + " - " + donneEntete["Tiers_adf2"] + " - " + donneEntete["Tiers_adfcp"] + "  " + donneEntete["Tiers_adf6"] + "\n" + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 7, Font.ITALIC)).SetUnderline(2, 2);
            Chunk ligneEspace = new Chunk("\n", FontFactory.GetFont(FontFactory.HELVETICA, 1, Font.ITALIC));

            pRécap.Add(contact);
            pRécap.Add(delai);
            pRécap.Add(ligneEspace);
            nouveauDocument.Add(pRécap);
            CurseurTemplate ct = new CurseurTemplate();

            valeurTemplate = ct.chercher("Devis");
            float[] largeurs =
            {
                int.Parse(valeurTemplate["Dimension1"]),
                int.Parse(valeurTemplate["Dimension2"]),
                int.Parse(valeurTemplate["Dimension3"]),
                int.Parse(valeurTemplate["Dimension4"]),
                int.Parse(valeurTemplate["Dimension5"]),
                int.Parse(valeurTemplate["Dimension6"]),
                int.Parse(valeurTemplate["Dimension7"]),
                int.Parse(valeurTemplate["Dimension8"]),
                int.Parse(valeurTemplate["Dimension9"])
            };                                                 // Dimension tableau body

            PdfPTable table = new PdfPTable(largeurs);

            table.TotalWidth  = 555;                                                                                                                               //Chaque colonne crée ci dessus doit être rempli
            table.LockedWidth = true;
            PdfPCell cellET1 = new PdfPCell(new Phrase("Article", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET1.Border = PdfPCell.NO_BORDER; //cellET1.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET1);
            PdfPCell cellET2 = new PdfPCell(new Phrase("Désignation", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET2.Border = PdfPCell.NO_BORDER; //cellET2.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET2);
            PdfPCell cellET3 = new PdfPCell(new Phrase("UV", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET3.Border = PdfPCell.NO_BORDER; //cellET3.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET3);
            PdfPCell cellET4 = new PdfPCell(new Phrase("Quantité", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET4.Border = PdfPCell.NO_BORDER; //cellET4.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET4);
            PdfPCell cellET5 = new PdfPCell(new Phrase("Prix remisé", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET5.Border = PdfPCell.NO_BORDER; //cellET5.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET5);
            PdfPCell cellET6 = new PdfPCell(new Phrase("Remise", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET6.Border = PdfPCell.NO_BORDER; //cellET6.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET6);
            PdfPCell cellET7 = new PdfPCell(new Phrase("Prix net", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET7.Border = PdfPCell.NO_BORDER; //cellET7.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET7);
            PdfPCell cellET8 = new PdfPCell(new Phrase("Montant HT", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET8.Border = PdfPCell.NO_BORDER; //cellET8.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET8);
            PdfPCell cellET9 = new PdfPCell(new Phrase("TVA", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellET9.Border = PdfPCell.NO_BORDER; //cellET9.Border += PdfPCell.BOTTOM_BORDER;

            table.AddCell(cellET9);
            Image image3 = Image.GetInstance(ConfigurationManager.AppSettings["CheminPatternTableau"]);

            image3.Alignment = Image.UNDERLYING;
            image3.SetAbsolutePosition(20, 567);
            nouveauDocument.Add(image3);
            int  i; int nbLigne = 0; float resultat = 0; float dimTab = 0; int décrement = 0; int numPage = 0;        //Constitution du tableau d'article
            bool okDési = false; bool okStart = false;

            for (i = 1; i <= iBody; i++)
            {
                //Condition ARTICLE----------------------------------------------------------------------------------------------------------------------
                if (donneeBody["Ligne_type" + i] == "ART")
                {
                    nbLigne++;
                    string   sPattern = "libelle" + i + "bis";
                    PdfPCell cell1    = new PdfPCell(new Phrase(donneeBody["Art_code" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell1.Border = PdfPCell.NO_BORDER; cell1.Border += PdfPCell.RIGHT_BORDER; cell1.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell1);
                    Paragraph pCell2 = new Paragraph();
                    PdfPCell  cell2  = new PdfPCell(pCell2); cell2.Border = PdfPCell.NO_BORDER; cell2.Border += PdfPCell.RIGHT_BORDER; cell2.Border += PdfPCell.LEFT_BORDER;
                    foreach (KeyValuePair <string, string> entry in donneeBody)
                    {
                        if (System.Text.RegularExpressions.Regex.IsMatch(entry.Key, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                        {
                            if (okStart == false)
                            {
                                pCell2.Add(new Phrase(donneeBody["Libelle" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD)));
                                string clé = entry.Key;
                                pCell2.Add(new Phrase(donneeBody[clé] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD)));
                                okStart = true;
                            }
                            else
                            {
                                string clé = entry.Key;
                                pCell2.Add(new Phrase(donneeBody[clé] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD)));
                            }
                            okDési = true;
                        }
                    }
                    if (okDési == false)
                    {
                        PdfPCell cell3 = new PdfPCell(new Phrase(donneeBody["Libelle" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell3.Border = PdfPCell.NO_BORDER; cell3.Border += PdfPCell.RIGHT_BORDER; cell3.Border += PdfPCell.LEFT_BORDER;
                        table.AddCell(cell3);
                    }
                    else
                    {
                        table.AddCell(cell2);
                    }
                    PdfPCell cell4 = new PdfPCell(new Phrase(donneeBody["Art_unite" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell4.Border = PdfPCell.NO_BORDER; cell4.Border += PdfPCell.RIGHT_BORDER; cell4.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell4);
                    PdfPCell cell5 = new PdfPCell(new Phrase(donneeBody["Art_qte" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell5.Border = PdfPCell.NO_BORDER; cell5.Border += PdfPCell.RIGHT_BORDER; cell5.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell5);
                    PdfPCell cell6 = new PdfPCell(new Phrase(donneeBody["Art_remise2" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell6.Border = PdfPCell.NO_BORDER; cell6.Border += PdfPCell.RIGHT_BORDER; cell6.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell6);
                    PdfPCell cell7 = new PdfPCell(new Phrase(donneeBody["Art_remise1" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell7.Border = PdfPCell.NO_BORDER; cell7.Border += PdfPCell.RIGHT_BORDER; cell7.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell7);
                    if (donneeBody["Art_prinet" + i] != "")
                    {
                        PdfPCell cell8 = new PdfPCell(new Phrase(double.Parse(donneeBody["Art_prinet" + i]).ToString("N2") + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell8.Border = PdfPCell.NO_BORDER; cell8.Border += PdfPCell.RIGHT_BORDER; cell8.Border += PdfPCell.LEFT_BORDER;
                        table.AddCell(cell8);
                    }
                    else
                    {
                        PdfPCell cell8 = new PdfPCell(new Phrase(donneeBody["Art_prinet" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell8.Border = PdfPCell.NO_BORDER; cell8.Border += PdfPCell.RIGHT_BORDER; cell8.Border += PdfPCell.LEFT_BORDER;
                        table.AddCell(cell8);
                    }
                    PdfPCell cell9 = new PdfPCell(new Phrase(donneeBody["Art_monht" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell9.Border = PdfPCell.NO_BORDER; cell9.Border += PdfPCell.RIGHT_BORDER; cell9.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell9);
                    PdfPCell cell10 = new PdfPCell(new Phrase("0" + donneeBody["Art_tva_code" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell10.Border = PdfPCell.NO_BORDER; cell10.Border += PdfPCell.RIGHT_BORDER; cell10.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell10);
                    okDési = false; okStart = false;
                }
                //Condition ARTICLE GRATUIT-----------------------------------------------------------------------------------------------------------------------------
                if (donneeBody["Ligne_type" + i] == "GRA")
                {
                    nbLigne++;
                    string   sPattern = "libelle" + i + "bis";
                    PdfPCell cell1    = new PdfPCell(new Phrase(donneeBody["Art_code" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell1.Border = PdfPCell.NO_BORDER; cell1.Border += PdfPCell.RIGHT_BORDER; cell1.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell1);
                    foreach (KeyValuePair <string, string> entry in donneeBody)
                    {
                        if (System.Text.RegularExpressions.Regex.IsMatch(entry.Key, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                        {
                            PdfPCell cell2 = new PdfPCell(new Phrase(donneeBody["Libelle" + i] + "\n" + donneeBody["Libelle" + i + "bis"] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell2.Border = PdfPCell.NO_BORDER; cell2.Border += PdfPCell.RIGHT_BORDER; cell2.Border += PdfPCell.LEFT_BORDER;
                            okDési = true;
                            table.AddCell(cell2);
                        }
                    }
                    if (okDési == false)
                    {
                        PdfPCell cell3 = new PdfPCell(new Phrase(donneeBody["Libelle" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell3.Border = PdfPCell.NO_BORDER; cell3.Border += PdfPCell.RIGHT_BORDER; cell3.Border += PdfPCell.LEFT_BORDER;
                        table.AddCell(cell3);
                    }
                    PdfPCell cell4 = new PdfPCell(new Phrase(donneeBody["Art_unite" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell4.Border = PdfPCell.NO_BORDER; cell4.Border += PdfPCell.RIGHT_BORDER; cell4.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell4);
                    PdfPCell cell5 = new PdfPCell(new Phrase(donneeBody["Art_qte" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell5.Border = PdfPCell.NO_BORDER; cell5.Border += PdfPCell.RIGHT_BORDER; cell5.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell5);
                    PdfPCell cell6 = new PdfPCell(new Phrase("" + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell6.Border = PdfPCell.NO_BORDER; cell6.Border += PdfPCell.RIGHT_BORDER; cell6.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell6);
                    table.AddCell(cell6);
                    table.AddCell(cell6);
                    PdfPCell cell7 = new PdfPCell((new Phrase(donneeBody["Lib_rempl_mt" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD)))); cell7.Border = PdfPCell.NO_BORDER; cell7.Border += PdfPCell.RIGHT_BORDER; cell7.Border += PdfPCell.LEFT_BORDER;
                    table.AddCell(cell7);
                    PdfPCell cell8 = new PdfPCell(new Phrase("" + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cell8.Border = PdfPCell.NO_BORDER; cell8.Border += PdfPCell.LEFT_BORDER; cell8.Border += PdfPCell.RIGHT_BORDER;
                    table.AddCell(cell8);
                }
                //Condition COMMENTAIRE--------------------------------------------------------------------------------------------------------------------------------
                if (donneeBody["Ligne_type" + i] == "COM")
                {
                    nbLigne++;
                    PdfPCell cellVide = new PdfPCell(new Phrase("" + "\n"));
                    PdfPCell cell     = new PdfPCell(new Phrase(donneeBody["Libelle" + i] + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD)));
                    PdfPCell cellFin  = new PdfPCell();
                    cellVide.Border  = PdfPCell.NO_BORDER;
                    cellVide.Border += PdfPCell.RIGHT_BORDER;
                    cellVide.Border += PdfPCell.LEFT_BORDER;
                    cell.Border      = PdfPCell.NO_BORDER;
                    cell.Border     += PdfPCell.RIGHT_BORDER;
                    cell.Border     += PdfPCell.LEFT_BORDER;
                    cellFin.Border   = PdfPCell.NO_BORDER;
                    cellFin.Border  += PdfPCell.LEFT_BORDER;
                    cellFin.Border  += PdfPCell.RIGHT_BORDER;
                    table.AddCell(cellVide);
                    table.AddCell(cell);
                    table.AddCell(cellVide);
                    table.AddCell(cellVide);
                    table.AddCell(cellVide);
                    table.AddCell(cellVide);
                    table.AddCell(cellVide);
                    table.AddCell(cellVide);
                    table.AddCell(cellFin);
                }
                PdfPCell cellEcartDroite = new PdfPCell(new Phrase(" " + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 2, Font.BOLD)));

                PdfPCell cellEcart = new PdfPCell(new Phrase(" " + "\n", FontFactory.GetFont(FontFactory.HELVETICA, 2, Font.BOLD)));
                cellEcart.Border        = PdfPCell.NO_BORDER;
                cellEcart.Border       += PdfPCell.LEFT_BORDER;
                cellEcart.Border       += PdfPCell.RIGHT_BORDER;
                cellEcartDroite.Border  = PdfPCell.NO_BORDER;
                cellEcartDroite.Border += PdfPCell.RIGHT_BORDER;
                cellEcartDroite.Border += PdfPCell.LEFT_BORDER;
                table.AddCell(cellEcartDroite); table.AddCell(cellEcart); table.AddCell(cellEcart); table.AddCell(cellEcart); table.AddCell(cellEcart); table.AddCell(cellEcart); table.AddCell(cellEcart); table.AddCell(cellEcart); table.AddCell(cellEcart);
                //--------------------------------------------GESTION DU SAUT DE PAGE-------------------------------------------------------------------------------------------
                //float temp = table.GetRowHeight(i-1-décrement);
                float temp = table.TotalHeight;
                dimTab = temp;
                if (dimTab >= 410 && i < iBody)
                {
                    //Saut de page
                    numPage++;
                    PdfPCell cellFin      = new PdfPCell(new Phrase(" "));
                    PdfPCell cellBlanche  = new PdfPCell(new Phrase(" "));
                    PdfPCell cellBlancheD = new PdfPCell(new Phrase(" "));
                    cellFin.Colspan          = 9;
                    cellBlanche.FixedHeight  = (450 - dimTab);
                    cellBlanche.Border       = PdfPCell.NO_BORDER;
                    cellBlanche.Border      += PdfPCell.RIGHT_BORDER;
                    cellBlanche.Border      += PdfPCell.LEFT_BORDER;
                    cellBlancheD.FixedHeight = (450 - dimTab);
                    cellBlancheD.Border      = PdfPCell.NO_BORDER;
                    cellBlancheD.Border     += PdfPCell.LEFT_BORDER;
                    cellBlancheD.Border     += PdfPCell.RIGHT_BORDER;
                    cellFin.Border           = PdfPCell.NO_BORDER;
                    cellFin.Border          += PdfPCell.TOP_BORDER;
                    table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlancheD);
                    table.AddCell(cellFin);
                    nouveauDocument.Add(table);//----------------------------------------------------------------------------Repère ligne en dessous--------------------------------------------------
                    Phrase pReport = new Phrase("                                                                                                                                                             A REPORTER\n\n\n\n\n                                                                                                                                                                    Page n° " + numPage, FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.BOLD));
                    nouveauDocument.Add(pReport);
                    table.DeleteBodyRows();
                    nouveauDocument.Add(Chunk.NEXTPAGE);
                    nouveauDocument.Add(tableau);
                    nouveauDocument.Add(pRécap);
                    nouveauDocument.Add(image2); nouveauDocument.Add(image3); nouveauDocument.Add(image5);
                    table.AddCell(cellET1); table.AddCell(cellET2); table.AddCell(cellET3); table.AddCell(cellET4); table.AddCell(cellET5); table.AddCell(cellET6); table.AddCell(cellET7); table.AddCell(cellET8); table.AddCell(cellET9);
                    dimTab    = 0;
                    décrement = (i - 1);
                }
                //----------------------------------------------------------------------------------------------------------------------------------------------------------------------
            }
            int b;                                          //----------------------------------------------------------------

            for (b = 0; b <= i; b++)                        //
            {                                               //              Compteur dimension du tableau
                float temp = table.TotalHeight;             //
                resultat = temp;                            //
            }                                               //-------------------------------------------------------------------
            if (i > iBody)
            {
                PdfPCell cellFin      = new PdfPCell(new Phrase(" "));
                PdfPCell cellBlanche  = new PdfPCell(new Phrase(" "));
                PdfPCell cellBlancheD = new PdfPCell(new Phrase(" "));
                cellFin.Colspan = 9;
                resultat        = 450 - resultat;   //<<----------450 correspond au nombre de point de la longueur du tableau, c'est la valeur à modifier pour modifier la taille du tableau

                cellBlanche.FixedHeight  = resultat;
                cellBlanche.Border       = PdfPCell.NO_BORDER;
                cellBlanche.Border      += PdfPCell.RIGHT_BORDER;
                cellBlanche.Border      += PdfPCell.LEFT_BORDER;
                cellBlancheD.FixedHeight = resultat;
                cellBlancheD.Border      = PdfPCell.NO_BORDER;
                cellBlancheD.Border     += PdfPCell.LEFT_BORDER;
                cellBlancheD.Border     += PdfPCell.RIGHT_BORDER;
                cellFin.Border           = PdfPCell.NO_BORDER;
                cellFin.Border          += PdfPCell.TOP_BORDER;
                table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlanche); table.AddCell(cellBlancheD);
                table.AddCell(cellFin);
            }
            nouveauDocument.Add(table);                                                                                        // Constitution tableau pied de page
            PdfPTable tableauPied = new PdfPTable(3);

            tableauPied.TotalWidth  = 555;
            tableauPied.LockedWidth = true;
            Paragraph pTVA = new Paragraph();

            pTVA.Add(new Phrase("Offre de prix valable jusqu'au : " + donneEntete["Date_val"], FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD, BaseColor.RED)));
            int iF = 0;

            foreach (KeyValuePair <string, string> entry in donneeFoot)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(entry.Value, "TVA", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    pTVA.Add(new Phrase("\nTVA " + donneeFoot.ElementAt(iF - 1).Value + " = " + entry.Value, FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD)));
                }
                iF++;
            }
            PdfPCell cellulePied = new PdfPCell(pTVA);

            cellulePied.Colspan = 2;
            cellulePied.Border  = PdfPCell.NO_BORDER;
            tableauPied.AddCell(cellulePied);
            nouveauDocument.Add(image4);
            PdfPTable tableauTot = new PdfPTable(1);
            PdfPCell  cellTTot   = new PdfPCell(new Phrase("Total HT : " + donneeFoot["Base_tva_mht"] + " €", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellTTot.Border = PdfPCell.NO_BORDER; cellTTot.Border = PdfPCell.BOTTOM_BORDER;

            tableauTot.AddCell(cellTTot);
            PdfPCell cellTVA = new PdfPCell(new Phrase("Total TVA : " + donneeFoot["Base_tva_mtva"] + " €", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellTVA.Border = PdfPCell.NO_BORDER; cellTVA.Border = PdfPCell.BOTTOM_BORDER;

            tableauTot.AddCell(cellTVA);
            PdfPCell cellTTC = new PdfPCell(new Phrase("Total TTC : " + donneeFoot["Base_tva_mttc"] + " €", FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD))); cellTTC.Border = PdfPCell.NO_BORDER;

            tableauTot.AddCell(cellTTC);
            PdfPCell cellTot = new PdfPCell(tableauTot);

            cellTot.Border = PdfPCell.NO_BORDER;
            tableauPied.AddCell(cellTot);
            nouveauDocument.Add(tableauPied);
            Phrase maPhrase = new Phrase();

            maPhrase.Add(new Chunk("\nBon pour accord ", FontFactory.GetFont(FontFactory.HELVETICA, 9, Font.BOLD)));
            maPhrase.Add(new Chunk("\n                 Fait à:                                le:                              Signature", FontFactory.GetFont(FontFactory.HELVETICA, 8)));
            nouveauDocument.Add(maPhrase);
            if (numPage > 0)
            {
                Phrase PageFinal = new Phrase("                                                                                                                                                                                                                                                                           Page n° " + (1 + numPage), FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.BOLD));
                nouveauDocument.Add(PageFinal);
            }
            nouveauDocument.Close();
            //Copie Doc dans GED
            try
            {
                String         connectionString = ConfigurationManager.AppSettings["ChaineDeConnexionBase"];
                OdbcConnection conn             = new OdbcConnection(connectionString);
                conn.Open();
                string         requete = "select T1.NOCLI c1 , T1.NOMCL c2 from B00C0ACR.AMAGESTCOM.ACLIENL1 T1 where T1.NOCLI = '" + donneEntete["Client_code"] + "'";
                OdbcCommand    act     = new OdbcCommand(requete, conn);
                OdbcDataReader act0    = act.ExecuteReader();
                string         nomADH  = "";
                while (act0.Read())
                {
                    nomADH = (act0.GetString(1));
                }
                conn.Close();
                if (!System.IO.Directory.Exists(ConfigurationManager.AppSettings["cheminGED"] + "\\" + donneEntete["Client_code"] + " - " + nomADH + "\\" + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("MMMM").First().ToString().ToUpper() + String.Join("", DateTime.Now.ToString("MMMM").Skip(1)) + "\\Devis\\"))
                {
                    System.IO.Directory.CreateDirectory(ConfigurationManager.AppSettings["cheminGED"] + "\\" + donneEntete["Client_code"] + " - " + nomADH + "\\" + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.ToString("MM").ToUpperInvariant() + "-" + DateTime.Now.ToString("MMMM").First().ToString().ToUpper() + String.Join("", DateTime.Now.ToString("MMMM").Skip(1)) + "\\Devis\\");
                    System.IO.File.Copy(chemin, ConfigurationManager.AppSettings["cheminGED"] + "\\" + donneEntete["Client_code"] + " - " + nomADH + "\\" + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.ToString("MM").ToUpperInvariant() + "-" + DateTime.Now.ToString("MMMM").First().ToString().ToUpper() + String.Join("", DateTime.Now.ToString("MMMM").Skip(1)) + "\\Devis\\" + "\\DEVIS_" + nomDoc + "_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".pdf");
                }
                else
                {
                    System.IO.File.Copy(chemin, ConfigurationManager.AppSettings["cheminGED"] + "\\" + donneEntete["Client_code"] + " - " + nomADH + "\\" + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.ToString("MM").ToUpperInvariant() + "-" + DateTime.Now.ToString("MMMM").First().ToString().ToUpper() + String.Join("", DateTime.Now.ToString("MMMM").Skip(1)) + "\\Devis\\" + "\\DEVIS_" + nomDoc + "_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".pdf");
                }
            }
            catch { }
            //--------------------------------------------------------FIN COPIE----------------------------------------------------------------------------------------------------------
            int nbImp = 0; int nbImpOK = 0;

            string[]         printer = new string[20]; // tableau qui contient les imprimantes du profil d'impression
            ProfilImprimante profil  = new ProfilImprimante();

            profil.chargementXML("Dev");         // chargement selon le type de doc
            string vendeur           = unProfil.Substring(2, 3);

            vendeur = vendeur.TrimEnd();
            var listeProfil = profil.getDonneeProfil();

            try
            {
                foreach (string v in listeProfil[vendeur])          //lecture des imprimantes liée à un profil
                {
                    printer[nbImp] = v.ToString();
                    nbImp++;                                        //on incrémente le nombre d'impression à executer
                }
            }
            catch
            {
                printer[nbImp] = ConfigurationManager.AppSettings["ImpDef"];                     //Imprimante par defaut (essai)
                nbImp++;
            }
            nbImp = nbImp - 1;
            while (nbImpOK <= nbImp)                            // boucle tant que le nombre d'impression fait n'à pas atteint le nombre d'impression demander
            {
                string printerName = printer[nbImpOK];
                string inputFile   = String.Format(@"{0}", chemin);
                try
                {
                    using (GhostscriptProcessor processor = new GhostscriptProcessor())
                    {
                        List <string> switches = new List <string>();
                        switches.Add("-empty");
                        switches.Add("-dPrinted");
                        switches.Add("-dBATCH");
                        switches.Add("-dNOPAUSE");
                        switches.Add("-dNOSAFER");
                        switches.Add("-dNumCopies=" + ConfigurationManager.AppSettings["NbCopieGC"]);
                        switches.Add("-sDEVICE=" + ConfigurationManager.AppSettings["PiloteImpressionGC"]);
                        switches.Add("-sOutputFile=%printer%" + printerName);
                        switches.Add("-f");
                        switches.Add(inputFile);

                        processor.StartProcessing(switches.ToArray(), null);
                    }
                    nbImpOK++;
                }
                catch (Exception e)
                { LogHelper.WriteToFile(e.Message, "ParseurBP" + donneEntete["Document_numero"].Trim()); }
            }

            /*Mail m = new Mail();
             * m.remplirDictionnaire();
             * m.comparerDocument(donneEntete["Client_code"]);*/
        }
Exemple #51
0
    private void CreateChunkSpawn(Chunk chunk, Vector2 startPos)
    {
        GameObject chunkParentBlock = new GameObject();

        chunkParentBlock.name = "Chunk: " + startPos.x + " / " + startPos.y;

        RenderedChunkData renderedChunkData = new RenderedChunkData();

        renderedChunkData.ChunkGameObject = chunkParentBlock;
        renderedChunkData.Position        = startPos;

        RenderedChunkData.Add(renderedChunkData);

        for (int y = 0; y < chunkSize.y; y++)
        {
            for (int x = 0; x < chunkSize.x; x++)
            {
                Vector2 checkPos = new Vector2(startPos.x + x, startPos.y + y);

                if (chunk.VoxelsInChunkData.TryGetValue(checkPos, out var voxelData))
                {
                    GameObject temp;

                    if (voxelData.Water)
                    {
                        //Spawn Water
                        temp = normalWaterBlock;
                    }
                    else if (voxelData.Sand)
                    {
                        temp = normalGroundSandBlock;
                    }
                    else
                    {
                        if (voxelData.BiomeType == BiomeTypes.Green)
                        {
                            temp = normalGroundBlock;
                        }
                        else if (voxelData.BiomeType == BiomeTypes.Saharah)
                        {
                            temp = normalGroundBlockSaharah;
                        }
                        else if (voxelData.BiomeType == BiomeTypes.Tundra)
                        {
                            temp = normalGroundBlockTundra;
                        }
                        else
                        {
                            Debug.LogError("Biome not set on voxel!!!!");
                            temp = null;
                        }
                    }

                    GameObject go = Instantiate(temp, checkPos, Quaternion.identity);


                    go.transform.SetParent(chunkParentBlock.transform);

                    GameObject Tree;

                    if (voxelData.Tree && voxelData.Land)
                    {
                        Tree = normalTreeGameObject;
                        GameObject goTree = Instantiate(Tree, checkPos, Quaternion.identity);
                        goTree.transform.SetParent(go.transform);
                    }

                    GameObject Grass;

                    if (voxelData.Grass && voxelData.Land)
                    {
                        var index = Random.Range(0, grassBlocks.Count);
                        Grass = grassBlocks[index];
                        GameObject goGrass = Instantiate(Grass, checkPos, Quaternion.identity);
                        goGrass.transform.SetParent(go.transform);
                    }

                    GameObject Flower;

                    if (voxelData.Flower && voxelData.Land)
                    {
                        Flower = normalFlowerGameObject;
                        GameObject goFlower = Instantiate(Flower, checkPos, Quaternion.identity);
                        goFlower.transform.SetParent(go.transform);
                    }

                    GameObject Bush;

                    if (voxelData.Bush && voxelData.Land)
                    {
                        Bush = normalBushGameObject;
                        GameObject goBush = Instantiate(Bush, checkPos, Quaternion.identity);
                        goBush.transform.SetParent(go.transform);
                    }
                }
            }
        }
    }
Exemple #52
0
        private static float IndentationCenter   = 220; //距左边距
        /// <summary>
        /// 绘制PDF
        /// </summary>
        /// <param name="FlowName">流程名</param>
        /// <param name="TaskId">流水号</param>
        /// <param name="ApplyName">申请人</param>
        /// <param name="Dept">申请部门</param>
        /// <param name="ApplyTime">申请时间</param>
        /// <param name="ProjectName">项目名</param>
        /// <param name="ProjectNo">项目编号</param>
        /// <param name="ImageNo">图片编号</param>
        /// <param name="ImageX">盖章X轴</param>
        /// <param name="ImageY">盖章Y轴</param>
        /// <param name="FlowId">流程Id</param>
        /// <param name="FilePath">水印图片路径</param>
        /// <param name="contentList">表单头数组</param>
        /// <param name="contentWithList">表单宽度数组</param>
        /// <param name="dtSourse">表单数据</param>
        /// <param name="dtApproveView">审批意见数据</param>
        ///  <param name="keyValuePairs">表单单列数据</param>
        ///  <param name="keyValuePairsHead">表单单列列头数据</param>
        public string GeneratePDF(string FlowName, string TaskId, string ApplyName, string Dept,
                                  string ApplyTime, string ProjectName, string ProjectNo, string ImageNo, float ImageX, float ImageY
                                  , List <string> contentList, float[] contentWithList
                                  , DataTable dtSourse, DataTable dtApproveView, Dictionary <string, string> keyValuePairs, Dictionary <string, string> keyValuePairsHead = null)
        {
            doc = new Document(PageSize.A4);
            try
            {
                string     fileName = string.Format("数据_{0}.pdf", DateTime.Now.ToString("yyyyMMddHHmmss"));
                string     filePath = string.Format("{0}UploadFile\\PDF\\{1}", AppDomain.CurrentDomain.BaseDirectory, fileName);
                FileStream fs       = new FileStream(filePath, FileMode.Create); //创建临时文件,到时生成好后删除
                PdfWriter  writer   = PdfWriter.GetInstance(doc, fs);
                writer.CloseStream = false;                                      //把doc内容写入流中
                doc.Open();

                iTextSharp.text.Image imageLogo = iTextSharp.text.Image.GetInstance(
                    string.Format(@"{0}\Content\images\单位LOGO.jpg", AppDomain.CurrentDomain.BaseDirectory));
                //imageLogo.Width = 100;
                imageLogo.SetAbsolutePosition(85, 780);
                writer.DirectContent.AddImage(imageLogo);

                AddHeaderTitleContent("泉州华中科技大学智能制造研究院", fontSmallest, 80);
                CreateEmptyRow(1); //生成一行空行
                CreateLine();      //生成一条下横线
                //CreateEmptyRow(1);//生成一行空行

                AddHeaderTitleContent(FlowName, fontSmallNoBold, IndentationCenter);//添加表头
                //CreateEmptyRow(1);//生成一行空行

                if (!string.IsNullOrEmpty(TaskId))
                {
                    AddPartnerContents("   流水号", TaskId, "申请人", ApplyName);
                }
                if (!string.IsNullOrEmpty(TaskId))
                {
                    AddPartnerContents("申请时间", ApplyTime.Substring(0, 10), "申请部门", Dept);
                }
                if (!string.IsNullOrEmpty(ProjectName))
                {
                    AddSinglePartnerContents("项目", ProjectNo + "-" + ProjectName);
                }
                if (keyValuePairsHead != null)
                {
                    foreach (var item in keyValuePairsHead.Keys)
                    {
                        AddSinglePartnerContents(item, keyValuePairsHead[item]);
                    }
                }
                AddPageNumberContent(); //添加页码
                CreateEmptyRow(1);      //生成一行空行

                //设置审批水印
                if (!string.IsNullOrEmpty(filePath))
                {
                    string ImgaePath = "";
                    if (ImageNo == "1")
                    {
                        ImgaePath = string.Format(@"{0}\Content\images\受控章.png", AppDomain.CurrentDomain.BaseDirectory);
                    }
                    if (ImageNo == "2")
                    {
                        ImgaePath = string.Format(@"{0}\Content\images\approveSmall.png", AppDomain.CurrentDomain.BaseDirectory);
                    }
                    if (ImageNo == "3")
                    {
                        ImgaePath = string.Format(@"{0}\Content\images\变更章.png", AppDomain.CurrentDomain.BaseDirectory);
                    }
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ImgaePath);
                    //image.SetAbsolutePosition(300, 650);
                    image.SetAbsolutePosition(ImageX, ImageY);
                    writer.DirectContent.AddImage(image);
                }


                #region 生成表格数据


                if (contentList != null)
                {
                    PdfPTable table = new PdfPTable(contentList.Count);

                    //添加表格列头
                    foreach (var item in contentList)
                    {
                        table.AddCell(GetPdfCell(item, fontTableSmallNoBold, Element.ALIGN_CENTER));
                    }
                    //添加表格列头宽度
                    table.SetTotalWidth(contentWithList);

                    if (dtSourse.Rows.Count > 0)
                    {
                        for (int i = 0; i < dtSourse.Rows.Count; i++)
                        {
                            table.AddCell(GetPdfCell((i + 1).ToString(), fontTableSmallNoBold, Element.ALIGN_CENTER));
                            for (int j = 0; j < dtSourse.Columns.Count; j++)
                            {
                                table.AddCell(GetPdfCell((dtSourse.Rows[i][j]).ToString(), fontTableSmallNoBold, Element.ALIGN_CENTER));
                            }
                        }
                    }
                    doc.Add(table);
                }
                #endregion

                #region 生成表格单行数据

                if (keyValuePairs != null)
                {
                    CreateEmptyRow(1);//生成一行空行
                    PdfPTable table = new PdfPTable(2);
                    float[]   fList = { 60, 200 };
                    table.SetTotalWidth(fList);
                    foreach (var item in keyValuePairs.Keys)
                    {
                        table.AddCell(GetPdfCell(item, fontTableSmallNoBold, Element.ALIGN_CENTER));
                        table.AddCell(GetPdfCell(keyValuePairs[item], fontTableSmallNoBold, Element.ALIGN_LEFT));
                    }
                    doc.Add(table);
                }

                #endregion

                #region 打印审批人

                CreateEmptyRow(1);//生成一行空行

                //int iResult = 1;  //每行打印数量

                if (dtApproveView.Rows.Count > 0)
                {
                    //int j = 0;
                    Paragraph content = new Paragraph();
                    for (int i = 0; i < dtApproveView.Rows.Count; i++)
                    {
                        content.IndentationLeft = IndentationLeft;
                        Chunk chunkName = new Chunk(dtApproveView.Rows[i]["NodeName"].ToString() + ":", fontSmallNoBold);
                        Chunk chunkText = new Chunk(dtApproveView.Rows[i]["NodePeople"].ToString(), fontSmallNoBold);
                        content.Add(0, chunkName);
                        content.Add(1, chunkText);
                        content.Alignment = 30;
                        //j++;
                        //if (i != 0 && i % iResult == 0 && i!= iResult)
                        //{
                        //    doc.Add(content);
                        //    j = 0;
                        //    content.Clear();
                        //}
                        doc.Add(content);
                        content.Clear();
                    }
                    //if (dtApproveView.Rows.Count <= iResult)
                    //{
                    //    doc.Add(content);
                    //    content.Clear();
                    //}
                }

                #endregion

                #region 添加文字水印
                string waterMarkName = "";

                #endregion

                doc.Close();
                MemoryStream ms = new MemoryStream();
                if (fs != null)
                {
                    byte[] bytes = new byte[fs.Length]; //定义一个长度为fs长度的字节数组
                    fs.Read(bytes, 0, (int)fs.Length);  //把fs的内容读到字节数组中
                    ms.Write(bytes, 0, bytes.Length);   //把字节内容读到流中
                    fs.Flush();
                    fs.Close();
                }
                MemoryStream waterMS = SetWaterMark(ms, filePath, waterMarkName);//先生成水印,再删除临时文件


                //if (File.Exists(filePath))//判断临时文件是否存在,如果存在则删除
                //{
                //    File.Delete(filePath);
                //    GC.Collect();//回收垃圾
                //}
                //SendFile(fileName, waterMS);//把PDF文件发送回浏览器

                return(filePath);
            }
            catch (DocumentException ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemple #53
0
 /// <summary>
 /// Generates chunk terrain for given chunk.
 /// </summary>
 /// <param name="chunk">The chunk to generate terrain for.</param>
 protected virtual void GenerateChunkTerrain(Chunk chunk)
 {
 }
Exemple #54
0
    private void CreateChunk(Vector2 startPos)
    {
        Chunk newChunk = new Chunk();

        newChunk.VoxelsInChunkData = new Dictionary <Vector2, VoxelData>();

        for (int y = 0; y < chunkSize.y; y++)
        {
            for (int x = 0; x < chunkSize.x; x++)
            {
                Vector2 voxelPos = new Vector2(startPos.x + x, startPos.y + y);

                float yCoord = (float)voxelPos.x / worldSize.x * scale;
                float xCoord = (float)voxelPos.y / worldSize.y * scale;

                float value = Mathf.PerlinNoise(xCoord, yCoord);

                VoxelData voxelData = new VoxelData();

                if (value > 0.5)
                {
                    int makeTree   = Random.Range(0, 100);
                    int makeGrass  = Random.Range(0, 50);
                    int makeFlower = Random.Range(0, 100);
                    int makeBush   = Random.Range(0, 100);

                    float valueBiome = Mathf.PerlinNoise(xCoord + 521F, yCoord + 2314F);

                    if (valueBiome > 0.6F)
                    {
                        voxelData.BiomeType = BiomeTypes.Green;
                    }
                    else if (valueBiome > 0.3)
                    {
                        voxelData.BiomeType = BiomeTypes.Saharah;
                    }
                    else
                    {
                        voxelData.BiomeType = BiomeTypes.Tundra;
                    }

                    #region Make Props

                    if (makeTree == 1 && voxelData.BiomeType != BiomeTypes.Saharah)
                    {
                        voxelData.Tree = true;
                    }
                    else if (makeGrass == 1)
                    {
                        voxelData.Grass = true;
                    }
                    else if (makeFlower == 1)
                    {
                        voxelData.Flower = true;
                    }

                    else if (makeBush == 1)
                    {
                        voxelData.Bush = true;
                    }

                    #endregion

                    voxelData.Land = true;
                }
                else if (value > 0.49)
                {
                    voxelData.Sand   = true;
                    voxelData.Tree   = false;
                    voxelData.Grass  = false;
                    voxelData.Flower = false;
                    voxelData.Bush   = false;
                }
                else
                {
                    voxelData.Water = true;
                }

                newChunk.VoxelsInChunkData.Add(voxelPos, voxelData);
            }
        }

        createdChunks.Add(startPos, newChunk);
    }
        private void ReadChunk(Chunk chunk, System.IO.Stream src, long origin)
        {
            long or;

            while (src.Position < chunk.length + origin)
            {
                var new_chunk = Chunk.FromStream(src);
                switch (new_chunk.id)
                {
                case ChunkId.EDIT3DS:
                    ReadChunk(new_chunk, src, src.Position);
                    break;

                case ChunkId.MESH_VERSION:
                    uint mesh_version = ReadInt(src);
                    break;

                case ChunkId.EDIT_OBJECT:
                    or           = src.Position;
                    current_name = ReadCStr(src);
                    ReadChunk(new_chunk, src, or);

                    break;

                case ChunkId.OBJ_TRIMESH:
                    ReadChunk(new_chunk, src, src.Position);

                    break;

                case ChunkId.TRI_VERTEXL:
                    ReadVertexList(src);
                    break;

                case ChunkId.TRI_FACEL1:
                    or = src.Position;
                    ReadIndexList(src);
                    SkipChunk(src);
                    SkipChunk(src);
                    if (vertex_list != null)
                    {
                        if (ret.VertexBuffer == null)
                        {
                            ret.VertexBuffer = new Glorg2.Graphics.OpenGL.VertexBuffer <VertexPositionTexCoordNormal>(VertexPositionTexCoordNormal.Descriptor);
                        }
                        ret.VertexBuffer.Add(vertex_list);
                        ModelPart part = new ModelPart();
                        part.Name        = current_name;
                        part.StartVertex = (int)index_offset;
                        part.VertexCount = vertex_list.Count;
                        part.IndexBuffer = new Glorg2.Graphics.OpenGL.IndexBuffer <uint>();
                        part.IndexBuffer.Add(index_list);
                        part.IndexBuffer.BufferData(Glorg2.Graphics.OpenGL.VboUsage.GL_STATIC_DRAW);
                        ret.Parts.Add(part);
                        index_offset += (uint)vertex_list.Count;
                        vertex_list   = null;
                        index_list    = null;
                    }
                    //ReadChunk(Chunk.FromStream(src), src);
                    //ReadChunk(new_chunk, src, or);
                    break;

                //case ChunkId.TRI_MA
                default:
                    // Chunk ignored, skip past it.
                    src.Seek(new_chunk.length - 6, SeekOrigin.Current);
                    break;
                }
            }
        }
Exemple #56
0
    IEnumerator CreateChunkNew(Chunk chunk, Vector2 startPos)
    {
        GameObject chunkParentBlock = new GameObject();

        chunkParentBlock.name = "Chunk: " + startPos.x + " / " + startPos.y;

        RenderedChunkData renderedChunkData = new RenderedChunkData();

        renderedChunkData.ChunkGameObject = chunkParentBlock;
        renderedChunkData.Position        = startPos;

        RenderedChunkData.Add(renderedChunkData);

        for (int y = 0; y < chunkSize.y; y++)
        {
            for (int x = 0; x < chunkSize.x; x++)
            {
                Vector2 checkPos = new Vector2(startPos.x + x, startPos.y + y);

                if (chunk.VoxelsInChunkData.TryGetValue(checkPos, out var voxelData))
                {
                    GameObject temp;

                    if (voxelData.Water)
                    {
                        //Spawn Water
                        temp = normalWaterBlock;
                    }
                    else if (voxelData.Sand)
                    {
                        temp = normalGroundSandBlock;
                    }
                    else
                    {
                        temp = normalGroundBlock;
                    }

                    GameObject go = Instantiate(temp, checkPos, Quaternion.identity);


                    go.transform.SetParent(chunkParentBlock.transform);

                    GameObject Tree;

                    if (voxelData.Tree && voxelData.Land)
                    {
                        Tree = normalTreeGameObject;
                        GameObject goTree = Instantiate(Tree, checkPos, Quaternion.identity);
                        goTree.transform.SetParent(go.transform);
                    }

                    GameObject Grass;

                    if (voxelData.Grass && voxelData.Land)
                    {
                        var index = Random.Range(0, grassBlocks.Count);
                        Grass = grassBlocks[index];
                        GameObject goGrass = Instantiate(Grass, checkPos, Quaternion.identity);
                        goGrass.transform.SetParent(go.transform);
                    }

                    GameObject Flower;

                    if (voxelData.Flower && voxelData.Land)
                    {
                        Flower = normalFlowerGameObject;
                        GameObject goFlower = Instantiate(Flower, checkPos, Quaternion.identity);
                        goFlower.transform.SetParent(go.transform);
                    }

                    GameObject Bush;

                    if (voxelData.Bush && voxelData.Land)
                    {
                        Bush = normalBushGameObject;
                        GameObject goBush = Instantiate(Bush, checkPos, Quaternion.identity);
                        goBush.transform.SetParent(go.transform);
                    }
                }
                yield return(new WaitForEndOfFrame());
            }
        }
    }
Exemple #57
0
    public void GetChunkData(Chunk chunk)
    {
        // Chunk global position.
        var Offset = chunk.Offset;

        // Settings !
        float         temperature     = TemperatureManager.GetTemperature(0 + (int)(Offset.x * ChunkSize.x), 0 + (int)(Offset.y * ChunkSize.z));
        float         humidity        = TemperatureManager.GetHumidity(0 + (int)(Offset.x * ChunkSize.x), 0 + (int)(Offset.y * ChunkSize.z));
        BiomeSettings CurrentSettings = BiomeManager.BestMatch(temperature, humidity);

        bool placedTree = false;

        for (int z = 0; z < ChunkSize.z; z += 1)
        {
            for (int x = 0; x < ChunkSize.x; x += 1)
            {
                temperature     = TemperatureManager.GetTemperature(x + (int)(chunk.Offset.x * ChunkSize.x), z + (int)(chunk.Offset.y * ChunkSize.z));
                humidity        = TemperatureManager.GetHumidity(x + (int)(chunk.Offset.x * ChunkSize.x), z + (int)(chunk.Offset.y * ChunkSize.z));
                CurrentSettings = BiomeManager.BestMatch(temperature, humidity);


                // Global position of the cube.
                int   gX          = ((int)Offset.x * (int)Chunk.ChunkSize.x) + x;
                int   gZ          = ((int)Offset.y * (int)Chunk.ChunkSize.z) + z;
                float noiseResult = ((Noise.GetNoise2d(gX, gZ) * CurrentSettings.TerrainAmplitude) + 1f) * (ChunkSize.y / 2);
                float height      = Mathf.Clamp(Mathf.Stepify(noiseResult, 1), 0, 254);

                // Default type
                BlockType type = CurrentSettings.DefaultBlocktype;

                // Filling under the chunk too.
                for (int i = 0; i <= height; i++)
                {
                    chunk.Voxels[x, i, z].Active = true;
                    chunk.Voxels[x, i, z].Type   = type;
                }

                // Big mountains?
                if (CurrentSettings.Mountains)
                {
                    GenerateMountains(chunk, x, z, (int)Mathf.Clamp(height, 0f, 254f));
                }

                // Add X layers of block on top of the generated rock.
                var pos = chunk.HighestAt(x, z);
                for (int i = 0; i < CurrentSettings.TopLayerThickness; i++)
                {
                    // Adding some dirt under top layer.
                    var newType = CurrentSettings.UnderLayerType;

                    // if highest block, its grass!
                    if (i == 0)
                    {
                        newType = CurrentSettings.TopLayerType;
                    }

                    // Placing block. Making sure its under 255 height.
                    chunk.Voxels[x, Mathf.Clamp(pos - i, 0, 254), z].Type = newType;
                }



                // Placing decoration
                int decorationChance = rng.RandiRange(1, 100);
                if (decorationChance < CurrentSettings.DecorationRate)
                {
                    // Placing point
                    int dy   = chunk.HighestAt(x, z) + 1;
                    var mesh = (ArrayMesh)ResourceLoader.Load(CurrentSettings.DecorationModel);
                    chunk.AddVoxelSprite(new VoxelSprite(mesh, new Vector3(x, dy, z)));
                }



                // Placing trees
                float treeChance = rng.RandfRange(1f, 100f);
                //GD.Print(treeChance + " <= " + CurrentSettings.TreeRate);
                if (treeChance < CurrentSettings.TreeRate)
                {
                    //GD.Print("Placed tree");
                    var file = (ArrayMesh)ResourceLoader.Load(CurrentSettings.TreeModel);

                    int ty = chunk.HighestAt(x, z) + 1;

                    //Placing point.

                    // Creating and setting the mesh.
                    var meshInstance = new MeshInstance();
                    meshInstance.Mesh = file;
                    meshInstance.Name = CurrentSettings.TreeModel;
                    // Adding it next frame.(safe with mutex lock)
                    CallDeferred("add_child", meshInstance);
                    // Moving it next frame(not in the tree yet :))
                    meshInstance.SetDeferred("translation", new Vector3(x + (Offset.x * ChunkSize.x) - 10, ty,
                                                                        z + (Offset.y * ChunkSize.z + 10)));
                    //meshInstance.SetDeferred("rotation_degrees", new Vector3(0, rng.RandfRange(0, 360), 0));
                }
            }
        }
    }
Exemple #58
0
        // Generate and populate the forest
        public override void Generate(Chunk chunkToPopulate)
        {
            // Set the constants
            name = "beach";
            normalTemperature = 70;
            normalWindSpeed   = 40;
            associatedColor   = "$oa";
            // Create a new random generator
            Random random = new Random();

            // Generate the chunks properties
            chunkToPopulate.windSpeed   = (normalWindSpeed * (random.Next(2, 8) / 5));
            chunkToPopulate.temperature = (normalTemperature * (random.Next(2, 4) / 3));

            #region Add minerals
            // the amont of sand
            int amontOfSand = random.Next(100, 200);

            for (int i = 0; i < amontOfSand; i++)
            {
                // Create a new piece of sand
                Minerals.MineralSand newIronOre = new Minerals.MineralSand();
                newIronOre.identifier.name             = "sand";
                newIronOre.identifier.isPluralAgnostic = true;
                chunkToPopulate.AddChild(newIronOre);
            }

            // Decide whether to generate flint
            if (random.Next(1, 8) == 1)
            {
                // the amont of flint
                int amontOfFlint = random.Next(1, 3);

                for (int i = 0; i < amontOfFlint; i++)
                {
                    // Create a new piece of boulder
                    Minerals.MineralFlint newFlint = new Minerals.MineralFlint();
                    chunkToPopulate.AddChild(newFlint);
                }
            }

            // Decide whether to generate rocks
            if (random.Next(1, 5) == 1)
            {
                // the amont of rocks
                int amontOfRocks = random.Next(1, 5);

                for (int i = 0; i < amontOfRocks; i++)
                {
                    // Create a new piece of rock
                    Minerals.MineralBasaltRock newRock = new Minerals.MineralBasaltRock();
                    chunkToPopulate.AddChild(newRock);
                }
            }

            // Decide whether to generate a shell
            if (random.Next(1, 100) == 1)
            {
                // Create a new shell
                Minerals.MineralMoonShell newMoonShell = new Minerals.MineralMoonShell();
                chunkToPopulate.AddChild(newMoonShell);
            }

            // Decide whether to generate a shell
            if (random.Next(1, 10) == 1)
            {
                // Create a new shell
                Minerals.MineralSandDollar newDollar = new Minerals.MineralSandDollar();
                chunkToPopulate.AddChild(newDollar);
            }

            // Decide whether to generate a shell
            if (random.Next(1, 10) == 1)
            {
                // Create a new shell
                Minerals.MineralCalicoScallopShell newScallopShell = new Minerals.MineralCalicoScallopShell();
                chunkToPopulate.AddChild(newScallopShell);
            }
            #endregion

            #region Add plants
            // the amont of palm trees
            int amontOfPalmTrees = random.Next(0, 3);

            for (int i = 0; i < amontOfPalmTrees; i++)
            {
                // Create a new Palm Trees
                Plants.PlantPalmTree newPalmTree = new Plants.PlantPalmTree();
                newPalmTree.identifier.name = "tree";

                // Make it eather short or tall
                if (random.Next(0, 1) == 0)
                {
                    newPalmTree.identifier.classifierAdjectives.Add("short");
                }
                else
                {
                    newPalmTree.identifier.classifierAdjectives.Add("tall");
                }

                newPalmTree.identifier.classifierAdjectives.Add("palm");
                chunkToPopulate.AddChild(newPalmTree);
            }

            // Decide whether to generate Seaweed
            if (random.Next(1, 5) == 1)
            {
                // the amont of seaweed
                int amontOfSeaweed = random.Next(1, 3);

                for (int i = 0; i < amontOfSeaweed; i++)
                {
                    // Create a new seaweed
                    Plants.PlantSeaweed newSeaweed = new Plants.PlantSeaweed();
                    newSeaweed.identifier.name = "seaweed";
                    chunkToPopulate.AddChild(newSeaweed);
                }
            }
            #endregion
        }
Exemple #59
0
    // Create each faces of a single voxel at pPositon in cPosition chunk.
    private void CreateVoxel(SurfaceTool pSurfaceTool, int x, int y, int z, Chunk pChunk)
    {
        // If no voxel is at position, skip
        if (!pChunk.Voxels[x, y, z].Active)
        {
            return;
        }

        // If block is next to each faces
        bool left   = x != 0 ? !pChunk.Voxels[x - 1, y, z].Active : true;
        bool right  = x != 15 ? !pChunk.Voxels[x + 1, y, z].Active : true;
        bool front  = z != 15 ? !pChunk.Voxels[x, y, z + 1].Active : true;
        bool back   = z != 0 ? !pChunk.Voxels[x, y, z - 1].Active : true;
        bool top    = y != 254 ? !pChunk.Voxels[x, y + 1, z].Active : true;
        bool bottom = y > 0 ? !pChunk.Voxels[x, y - 1, z].Active : true;

        // If voxel is completly surrounded
        if (left && right && front && back && top && bottom)
        {
            return;
        }

        // If the voxel is on the side of a chunk. Check in the neighbor chunk.
        bool left2  = (x == 0 && PreloadedChunks[new Vector2(pChunk.Offset - new Vector2(1, 0))].Voxels[15, y, z].Active);
        bool right2 = (x == 15 && PreloadedChunks[new Vector2(pChunk.Offset + new Vector2(1, 0))].Voxels[0, y, z].Active);
        bool back2  = (z == 0 && PreloadedChunks[new Vector2(pChunk.Offset - new Vector2(0, 1))].Voxels[x, y, 15].Active);
        bool front2 = (z == 15 && PreloadedChunks[new Vector2(pChunk.Offset + new Vector2(0, 1))].Voxels[x, y, 0].Active);

        // Set right type
        var type = pChunk.Voxels[x, y, z].Type;

        // Local position of the voxel.
        Vector3 vertextOffset = new Vector3(x, y, z);

        // Get colors
        var color = GetVoxelColor(pChunk, vertextOffset, type);

        pSurfaceTool.AddColor(color);

        if (top) // Above
        {
            pSurfaceTool.AddNormal(new Vector3(0, 1, 0));
            pSurfaceTool.AddVertex(Vertices[4] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[5] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[7] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[5] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[6] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[7] + vertextOffset);
        }
        if (right && !right2) // Right
        {
            pSurfaceTool.AddNormal(new Vector3(1, 0, 0));
            pSurfaceTool.AddVertex(Vertices[2] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[5] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[1] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[2] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[6] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[5] + vertextOffset);
        }
        if (left && !left2) // Left
        {
            pSurfaceTool.AddNormal(new Vector3(-1, 0, 0));
            pSurfaceTool.AddVertex(Vertices[0] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[7] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[3] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[0] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[4] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[7] + vertextOffset);
        }
        if (front && !front2) // Front
        {
            pSurfaceTool.AddNormal(new Vector3(0, 0, 1));
            pSurfaceTool.AddVertex(Vertices[3] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[6] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[2] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[3] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[7] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[6] + vertextOffset);
        }
        if (back && !back2) // Above
        {
            pSurfaceTool.AddNormal(new Vector3(0, 0, -1));
            pSurfaceTool.AddVertex(Vertices[0] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[1] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[5] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[5] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[4] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[0] + vertextOffset);
        }
        if (bottom && y != 0)
        {
            pSurfaceTool.AddNormal(new Vector3(0, 1, 0));
            pSurfaceTool.AddVertex(Vertices[1] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[3] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[2] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[1] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[0] + vertextOffset);
            pSurfaceTool.AddVertex(Vertices[3] + vertextOffset);
        }
    }
        private void SkipChunk(Stream src)
        {
            Chunk ch = Chunk.FromStream(src);

            src.Seek(ch.length - 6, SeekOrigin.Current);
        }