grid.gd 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # This script creates the ImageTexture and assigns it to an existing material at runtime.
  2. # By not having `@tool`, this avoids saving the raw image data in the scene file,
  3. # which would make it much larger.
  4. extends MeshInstance3D
  5. const TEXTURE_SIZE = Vector2i(512, 512)
  6. const GRID_SIZE = 32
  7. const GRID_THICKNESS = 4
  8. func _ready() -> void:
  9. var image := Image.create(TEXTURE_SIZE.x, TEXTURE_SIZE.y, false, Image.FORMAT_RGB8)
  10. # Use 1-dimensional loop as it's faster than a nested loop.
  11. for i in TEXTURE_SIZE.x * TEXTURE_SIZE.y:
  12. var x := i % TEXTURE_SIZE.y
  13. var y := i / TEXTURE_SIZE.y
  14. var color := Color()
  15. # Draw a grid with more contrasted points where X and Y lines meet.
  16. # Center the grid's lines so that lines are visible on all the texture's edges.
  17. if (x + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS and (y + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS:
  18. color.g = 0.8
  19. elif (x + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS or (y + GRID_THICKNESS / 2) % GRID_SIZE < GRID_THICKNESS:
  20. color.g = 0.25
  21. # Add some random noise for detail.
  22. color += Color(randf(), randf(), randf()) * 0.1
  23. image.set_pixel(x, y, color)
  24. image.generate_mipmaps()
  25. var image_texture := ImageTexture.create_from_image(image)
  26. get_surface_override_material(0).albedo_texture = image_texture
  27. image.bump_map_to_normal_map(5.0)
  28. image.generate_mipmaps()
  29. var image_texture_normal := ImageTexture.create_from_image(image)
  30. get_surface_override_material(0).normal_texture = image_texture_normal