EditorTerrain.as 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. // Urho3D terrain editor
  2. const uint TERRAIN_EDITMODE_RAISELOWERHEIGHT = 0, TERRAIN_EDITMODE_SETHEIGHT = 1, TERRAIN_EDITMODE_SMOOTHHEIGHT = 3,
  3. TERRAIN_EDITMODE_PAINTBRUSH = 4, TERRAIN_EDITMODE_PAINTTREES = 5, TERRAIN_EDITMODE_PAINTFOLIAGE = 6;
  4. funcdef bool TerrainEditorShowCallback();
  5. class TerrainEditorUpdateChanges {
  6. IntVector2 offset;
  7. Image@ oldImage;
  8. Image@ newImage;
  9. }
  10. class TerrainEditorBrushVisualizer
  11. {
  12. Node@ node;
  13. CustomGeometry@ customGeometry;
  14. private bool addedToOctree = false;
  15. void Create()
  16. {
  17. node = Node();
  18. customGeometry = node.CreateComponent("CustomGeometry");
  19. customGeometry.numGeometries = 1;
  20. customGeometry.material = cache.GetResource("Material", "Materials/VColUnlit.xml");
  21. customGeometry.occludee = false;
  22. customGeometry.enabled = true;
  23. }
  24. void Hide()
  25. {
  26. node.enabled = false;
  27. addedToOctree = false;
  28. }
  29. void Update(Terrain@ terrainComponent, Vector3 position, float radius)
  30. {
  31. node.enabled = true;
  32. node.position = Vector3(position.x, 0, position.z);
  33. // Generate the circle
  34. customGeometry.BeginGeometry(0, LINE_STRIP);
  35. for (uint i = 0; i < 364; i += 4)
  36. {
  37. float angle = i * M_PI / 180;
  38. float x = radius * Cos(angle / 0.0174532925);
  39. float z = radius * Sin(angle / 0.0174532925);
  40. float y = terrainComponent.GetHeight(Vector3(position.x + x, 0, position.z + z));
  41. customGeometry.DefineVertex(Vector3(x, y + 0.25, z));
  42. customGeometry.DefineColor(Color(0, 1, 0));
  43. }
  44. customGeometry.Commit();
  45. if (editorScene.octree !is null && addedToOctree == false)
  46. {
  47. editorScene.octree.AddManualDrawable(customGeometry);
  48. addedToOctree = true;
  49. }
  50. }
  51. }
  52. class TerrainEditor
  53. {
  54. private bool dirty = true;
  55. private uint editMode = 0;
  56. private Window@ window;
  57. private UIElement@ toolbar;
  58. private Text@ currentToolDescText;
  59. private Array<Image@> brushes;
  60. private CheckBox@ selectedBrush;
  61. private Image@ selectedBrushImage;
  62. private Image@ scaledSelectedBrushImage;
  63. private Slider@ brushSizeSlider;
  64. private Slider@ brushOpacitySlider;
  65. private Slider@ brushHeightSlider;
  66. private TerrainEditorBrushVisualizer brushVisualizer;
  67. private Array<Terrain@> terrainsEdited;
  68. private Color targetColor;
  69. bool targetColorSelected = false;
  70. // Create the Terrain Editor window and initialize it
  71. void Create()
  72. {
  73. if (window !is null)
  74. return;
  75. window = LoadEditorUI("UI/EditorTerrainWindow.xml");
  76. ui.root.AddChild(window);
  77. window.opacity = uiMaxOpacity;
  78. BorderImage@ currentToolDesc = window.GetChild("CurrentToolDesc", true);
  79. currentToolDesc.layoutBorder = IntRect(8, 8, 8, 8);
  80. currentToolDescText = window.GetChild("CurrentToolDescText", true);
  81. ListView@ brushesContainer = window.GetChild("BrushesContainer", true);
  82. brushesContainer.SetScrollBarsVisible(true, false);
  83. brushesContainer.contentElement.layoutMode = LM_HORIZONTAL;
  84. brushesContainer.SetFixedHeight(84);
  85. BorderImage@ settingsArea = window.GetChild("SettingsArea", true);
  86. settingsArea.layoutBorder = IntRect(8, 8, 8, 8);
  87. LineEdit@ createTerrainValue = window.GetChild("CreateTerrainValue", true);
  88. createTerrainValue.text = "1024";
  89. brushSizeSlider = window.GetChild("BrushSize", true);
  90. brushOpacitySlider = window.GetChild("BrushOpacity", true);
  91. brushHeightSlider = window.GetChild("BrushHeight", true);
  92. window.height = 300;
  93. window.SetPosition(ui.root.width - 10 - window.width, attributeInspectorWindow.position.y + attributeInspectorWindow.height + 10);
  94. SubscribeToEvent(window.GetChild("RaiseLowerHeight", true), "Toggled", "OnEditModeSelected");
  95. SubscribeToEvent(window.GetChild("SetHeight", true), "Toggled", "OnEditModeSelected");
  96. SubscribeToEvent(window.GetChild("SmoothHeight", true), "Toggled", "OnEditModeSelected");
  97. //SubscribeToEvent(window.GetChild("PaintBrush", true), "Toggled", "OnEditModeSelected");
  98. //SubscribeToEvent(window.GetChild("PaintTrees", true), "Toggled", "OnEditModeSelected");
  99. //SubscribeToEvent(window.GetChild("PaintFoliage", true), "Toggled", "OnEditModeSelected");
  100. SubscribeToEvent(window.GetChild("CloseButton", true), "Released", "Hide");
  101. SubscribeToEvent(window.GetChild("CreateTerrainButton", true), "Released", "CreateTerrain");
  102. SubscribeToEvent(window.GetChild("ResetButton", true), "Released", "ResetWindow");
  103. SubscribeToEvent(brushSizeSlider, "DragEnd", "UpdateScaledBrush");
  104. LoadBrushes();
  105. Show();
  106. brushVisualizer.Create();
  107. }
  108. void ResetWindow()
  109. {
  110. // Reset edit mode to default
  111. SetEditMode(TERRAIN_EDITMODE_RAISELOWERHEIGHT, "Raise or lower terrain");
  112. // Clear selected brush
  113. ClearSelectedBrush();
  114. }
  115. void ClearSelectedBrush()
  116. {
  117. selectedBrush = null;
  118. selectedBrushImage = null;
  119. scaledSelectedBrushImage = null;
  120. ListView@ terrainBrushes = window.GetChild("BrushesContainer", true);
  121. for (uint i = 0; i < terrainBrushes.numItems; ++i)
  122. {
  123. CheckBox@ checkbox = cast<CheckBox>(terrainBrushes.items[i]);
  124. checkbox.checked = false;
  125. checkbox.enabled = true;
  126. }
  127. }
  128. // Hide the window
  129. void Hide()
  130. {
  131. ClearSelectedBrush();
  132. window.visible = false;
  133. }
  134. void HideBrushVisualizer()
  135. {
  136. brushVisualizer.Hide();
  137. }
  138. void UpdateBrushVisualizer(Terrain@ terrainComponent, Vector3 position)
  139. {
  140. if (scaledSelectedBrushImage is null)
  141. {
  142. brushVisualizer.Hide();
  143. return;
  144. }
  145. if (window.visible == true)
  146. brushVisualizer.Update(terrainComponent, position, scaledSelectedBrushImage.width / 2);
  147. }
  148. // Save all the terrains we have edited
  149. void Save()
  150. {
  151. for (uint i = 0; i < terrainsEdited.length; ++i)
  152. {
  153. // Make sure its not null (it may have been deleted since last save)
  154. if (terrainsEdited[i] !is null)
  155. {
  156. String fileLocation = sceneResourcePath + terrainsEdited[i].GetAttribute("Height Map").GetResourceRef().name;
  157. Array<String> chunks = fileLocation.Split('/');
  158. Array<String> parts = chunks[chunks.length - 1].Split('.');
  159. String fileType = parts[1];
  160. if (fileType == "png")
  161. {
  162. terrainsEdited[i].heightMap.SavePNG(fileLocation);
  163. }
  164. else if (fileType == "jpg")
  165. {
  166. // Save with the highest quality
  167. terrainsEdited[i].heightMap.SaveJPG(fileLocation, 100);
  168. }
  169. else if (fileType == "bmp")
  170. {
  171. terrainsEdited[i].heightMap.SaveBMP(fileLocation);
  172. }
  173. else if (fileType == "tga")
  174. {
  175. terrainsEdited[i].heightMap.SaveTGA(fileLocation);
  176. }
  177. }
  178. }
  179. // Clean up terrainsEdited array by clearing it
  180. // (this will remove any terrains that may have been deleted)
  181. terrainsEdited.Clear();
  182. }
  183. // Show the window
  184. bool Show()
  185. {
  186. window.visible = true;
  187. window.BringToFront();
  188. return true;
  189. }
  190. // Update the UI
  191. void UpdateDirty()
  192. {
  193. if (!dirty)
  194. return;
  195. CheckBox@ raiseLowerHeight = window.GetChild("RaiseLowerHeight", true);
  196. CheckBox@ setHeight = window.GetChild("SetHeight", true);
  197. CheckBox@ smoothHeight = window.GetChild("SmoothHeight", true);
  198. //CheckBox@ paintBrush = window.GetChild("PaintBrush", true);
  199. //CheckBox@ paintTrees = window.GetChild("PaintTrees", true);
  200. //CheckBox@ paintFoliage = window.GetChild("PaintFoliage", true);
  201. raiseLowerHeight.checked = (editMode == TERRAIN_EDITMODE_RAISELOWERHEIGHT) ? true : false;
  202. setHeight.checked = (editMode == TERRAIN_EDITMODE_SETHEIGHT) ? true : false;
  203. smoothHeight.checked = (editMode == TERRAIN_EDITMODE_SMOOTHHEIGHT) ? true : false;
  204. //paintBrush.checked = (editMode == TERRAIN_EDITMODE_PAINTBRUSH) ? true : false;
  205. //paintTrees.checked = (editMode == TERRAIN_EDITMODE_PAINTTREES) ? true : false;
  206. //paintFoliage.checked = (editMode == TERRAIN_EDITMODE_PAINTFOLIAGE) ? true : false;
  207. raiseLowerHeight.enabled = !raiseLowerHeight.checked;
  208. setHeight.enabled = !setHeight.checked;
  209. smoothHeight.enabled = !smoothHeight.checked;
  210. ListView@ terrainBrushes = window.GetChild("BrushesContainer", true);
  211. for (uint i = 0; i < terrainBrushes.numItems; ++i)
  212. {
  213. CheckBox@ checkbox = cast<CheckBox>(terrainBrushes.items[i]);
  214. checkbox.checked = terrainBrushes.items[i] is selectedBrush;
  215. checkbox.enabled = !checkbox.checked;
  216. }
  217. dirty = false;
  218. }
  219. // This gets called when we want to do something to a terrain
  220. void Work(Terrain@ terrainComponent, Vector3 position)
  221. {
  222. // Only work if a brush is selected
  223. if (selectedBrushImage is null || scaledSelectedBrushImage is null || window.visible == false)
  224. return;
  225. SetSceneModified();
  226. // Add that terrain to the terrainsEdited if its not already in there
  227. if (terrainsEdited.FindByRef(terrainComponent) == -1)
  228. terrainsEdited.Push(terrainComponent);
  229. TerrainEditorUpdateChanges@ updateChanges = TerrainEditorUpdateChanges();
  230. IntVector2 pos = terrainComponent.WorldToHeightMap(position);
  231. switch (editMode)
  232. {
  233. case TERRAIN_EDITMODE_RAISELOWERHEIGHT:
  234. UpdateTerrainRaiseLower(terrainComponent.heightMap, pos, updateChanges);
  235. break;
  236. case TERRAIN_EDITMODE_SETHEIGHT:
  237. UpdateTerrainSetHeight(terrainComponent.heightMap, pos, updateChanges);
  238. break;
  239. case TERRAIN_EDITMODE_SMOOTHHEIGHT:
  240. UpdateTerrainSmooth(terrainComponent.heightMap, pos, updateChanges);
  241. break;
  242. }
  243. terrainComponent.ApplyHeightMap();
  244. UpdateBrushVisualizer(terrainComponent, position);
  245. ModifyTerrainAction action;
  246. action.Define(terrainComponent, updateChanges.offset, updateChanges.oldImage, updateChanges.newImage);
  247. SaveEditAction(action);
  248. }
  249. private uint NearestPowerOf2(uint value) {
  250. if (value < 2)
  251. return 2;
  252. for (uint i = 1; i <= 2048; i *= 2)
  253. {
  254. if (value == i)
  255. return i;
  256. if (value < i || value > i * 2)
  257. continue;
  258. return value < (i + (i / 2)) ? i : i * 2;
  259. }
  260. return 2048;
  261. }
  262. private void CreateTerrain()
  263. {
  264. String fileName = "Textures/heightmap-" + time.timeSinceEpoch + ".png";
  265. String fileLocation = sceneResourcePath + fileName;
  266. Node@ node = CreateNode(LOCAL);
  267. node.position = Vector3(0, 0, 0);
  268. LineEdit@ lineEdit = window.GetChild("CreateTerrainValue", true);
  269. uint lineEditLength = lineEdit.text.Trimmed().ToUInt();
  270. // The parse failed, so use a decent default
  271. if (lineEditLength == 0)
  272. lineEditLength = 1024;
  273. Image@ image = Image();
  274. uint length = NearestPowerOf2(lineEditLength) + 1;
  275. image.SetSize(length, length, 3);
  276. UpdateTerrainSetConstantHeight(image, 0);
  277. if (!fileSystem.DirExists(GetPath(fileLocation)))
  278. fileSystem.CreateDir(GetPath(fileLocation));
  279. image.SavePNG(fileLocation);
  280. Terrain@ terrain = node.CreateComponent("Terrain");
  281. terrain.heightMap = image;
  282. Resource@ res = cache.GetResource("Image", fileLocation);
  283. ResourceRef ref = ResourceRef();
  284. ref.type = res.type;
  285. ref.name = fileName;
  286. terrain.SetAttribute("Height Map", Variant(ref));
  287. terrain.ApplyAttributes();
  288. SelectComponent(terrain, false);
  289. }
  290. // Utility function, returns the difference of the two numbers
  291. private float Difference(float a, float b)
  292. {
  293. return (a > b) ? a - b : b - a;
  294. }
  295. // Returns a brush based on its name (its filename minus the extension)
  296. private Image@ GetBrushImage(String brushName)
  297. {
  298. for (uint i = 0; i < brushes.length; ++i)
  299. {
  300. if (brushes[i].name == brushName)
  301. {
  302. return brushes[i];
  303. }
  304. }
  305. return null;
  306. }
  307. // Creates a brush element
  308. private UIElement@ LoadBrush(String fileLocation)
  309. {
  310. Array<String> chunks = fileLocation.Split('/');
  311. Array<String> parts = chunks[chunks.length - 1].Split('.');
  312. // We use this when editing the terrain
  313. Image@ image = cache.GetResource("Image", fileLocation);
  314. if (image is null)
  315. return null;
  316. image.name = parts[0];
  317. brushes.Push(image);
  318. // This is for the brush icon
  319. Texture2D@ texture = cache.GetResource("Texture2D", fileLocation);
  320. CheckBox@ brush = CheckBox(parts[0]);
  321. brush.defaultStyle = uiStyle;
  322. brush.style = "TerrainEditorCheckbox";
  323. brush.SetFixedSize(64, 64);
  324. SubscribeToEvent(brush, "Toggled", "OnBrushSelected");
  325. BorderImage@ icon = BorderImage("Icon");
  326. icon.defaultStyle = iconStyle;
  327. icon.texture = texture;
  328. icon.imageRect = IntRect(0, 0, texture.width, texture.height);
  329. icon.SetFixedSize(64, 64);
  330. brush.AddChild(icon);
  331. return brush;
  332. }
  333. // Loads all the brushes from a hard-coded folder
  334. private void LoadBrushes()
  335. {
  336. ListView@ terrainBrushes = window.GetChild("BrushesContainer", true);
  337. String brushPath = "Textures/Editor/TerrainBrushes/";
  338. Array<String>@ resourceDirs = cache.resourceDirs;
  339. String brushesFileLocation;
  340. for (uint i = 0; i < resourceDirs.length; ++i)
  341. {
  342. brushesFileLocation = resourceDirs[i] + brushPath;
  343. if (fileSystem.DirExists(brushesFileLocation))
  344. break;
  345. }
  346. if (brushesFileLocation.empty)
  347. return;
  348. Array<String> files = fileSystem.ScanDir(brushesFileLocation, "*.*", SCAN_FILES, false);
  349. for (uint i = 0; i < files.length; ++i)
  350. {
  351. UIElement@ brush = LoadBrush(brushPath + files[i]);
  352. if (brush !is null)
  353. terrainBrushes.AddItem(brush);
  354. }
  355. }
  356. private void OnEditModeSelected(StringHash eventType, VariantMap& eventData)
  357. {
  358. CheckBox@ edit = eventData["Element"].GetPtr();
  359. if (!edit.checked)
  360. return;
  361. if (edit.name == "RaiseLowerHeight")
  362. SetEditMode(TERRAIN_EDITMODE_RAISELOWERHEIGHT, "Raise or lower terrain");
  363. else if (edit.name == "SetHeight")
  364. SetEditMode(TERRAIN_EDITMODE_SETHEIGHT, "Set height to specified height");
  365. else if (edit.name == "SmoothHeight")
  366. SetEditMode(TERRAIN_EDITMODE_SMOOTHHEIGHT, "Smooth the terrain");
  367. else if (edit.name == "PaintBrush")
  368. SetEditMode(TERRAIN_EDITMODE_PAINTBRUSH, "Paint textures onto the terrain");
  369. else if (edit.name == "PaintTrees")
  370. SetEditMode(TERRAIN_EDITMODE_PAINTTREES, "Paint trees onto the terrain");
  371. else if (edit.name == "PaintFoliage")
  372. SetEditMode(TERRAIN_EDITMODE_PAINTFOLIAGE, "Paint foliage onto the terrain");
  373. }
  374. private void OnBrushSelected(StringHash eventType, VariantMap& eventData)
  375. {
  376. CheckBox@ checkbox = cast<CheckBox>(eventData["Element"].GetPtr());
  377. if (checkbox.checked == false)
  378. return;
  379. selectedBrush = checkbox;
  380. selectedBrushImage = GetBrushImage(selectedBrush.name);
  381. UpdateScaledBrush();
  382. dirty = true;
  383. }
  384. private void SetEditMode(uint mode, String description)
  385. {
  386. window.GetChild("BrushOpacityLabel", true).visible = (mode == TERRAIN_EDITMODE_RAISELOWERHEIGHT);
  387. window.GetChild("BrushHeightLabel", true).visible = (mode == TERRAIN_EDITMODE_SETHEIGHT);
  388. window.GetChild("BrushOpacity", true).visible = (mode == TERRAIN_EDITMODE_RAISELOWERHEIGHT);
  389. window.GetChild("BrushHeight", true).visible = (mode == TERRAIN_EDITMODE_SETHEIGHT);
  390. editMode = mode;
  391. currentToolDescText.text = description;
  392. dirty = true;
  393. // force the window to resize its height to fit its children
  394. window.height = 0;
  395. }
  396. // Utility function, returns the smaller of the two numbers
  397. private float Smaller(float a, float b)
  398. {
  399. return (a > b) ? b : a;
  400. }
  401. private void UpdateScaledBrush()
  402. {
  403. if (selectedBrushImage is null)
  404. return;
  405. float size = (brushSizeSlider.value / 25) + 0.5;
  406. scaledSelectedBrushImage = selectedBrushImage.GetSubimage(IntRect(0, 0, selectedBrushImage.width, selectedBrushImage.height));
  407. scaledSelectedBrushImage.Resize(int(selectedBrushImage.width * size), int(selectedBrushImage.height * size));
  408. }
  409. private void UpdateTerrainRaiseLower(Image@ terrainImage, IntVector2 position, TerrainEditorUpdateChanges@ updateChanges)
  410. {
  411. uint brushImageWidth = scaledSelectedBrushImage.width;
  412. uint brushImageHeight = scaledSelectedBrushImage.height;
  413. updateChanges.offset = IntVector2(position.x - (brushImageWidth / 2), position.y - (brushImageHeight / 2));
  414. if (updateChanges.offset.x < 0) updateChanges.offset.x = 0;
  415. if (updateChanges.offset.y < 0) updateChanges.offset.y = 0;
  416. IntRect boundsRect = IntRect(updateChanges.offset.x, updateChanges.offset.y, updateChanges.offset.x + brushImageWidth, updateChanges.offset.y + brushImageHeight);
  417. boundsRect = ClipIntRectToHeightmapBounds(terrainImage, boundsRect);
  418. updateChanges.oldImage = terrainImage.GetSubimage(boundsRect);
  419. // lower or raise (respectively), multiply this by the brush opacity
  420. float opacity = brushOpacitySlider.value / 25;
  421. float modifier = (input.keyDown[KEY_SHIFT] ? -opacity : opacity) * 0.05;
  422. // Iterate over the entire brush image
  423. for (int y = 0; y < brushImageHeight; ++y)
  424. {
  425. for (int x = 0; x < brushImageWidth; ++x)
  426. {
  427. // Get the current terrain height at that position (centred to the brush's size)
  428. IntVector2 pos = IntVector2(position.x + x - (brushImageWidth / 2), position.y + y - (brushImageHeight / 2));
  429. Color newColor = terrainImage.GetPixel(pos.x, pos.y);
  430. Color brushColor = scaledSelectedBrushImage.GetPixel(x, y);
  431. // Now apply the brush to the terrain (we only use the alpha)
  432. newColor.r += brushColor.a * modifier;
  433. newColor.g += brushColor.a * modifier;
  434. newColor.b += brushColor.a * modifier;
  435. terrainImage.SetPixel(pos.x, pos.y, newColor);
  436. }
  437. }
  438. // Smooth the terrain a bit
  439. TerrainEditorUpdateChanges@ smoothUpdateChanges = TerrainEditorUpdateChanges();
  440. UpdateTerrainSmooth(terrainImage, position, smoothUpdateChanges);
  441. updateChanges.newImage = smoothUpdateChanges.newImage;
  442. }
  443. private void UpdateTerrainSmooth(Image@ terrainImage, IntVector2 position, TerrainEditorUpdateChanges@ updateChanges)
  444. {
  445. uint brushImageWidth = scaledSelectedBrushImage.width;
  446. uint brushImageHeight = scaledSelectedBrushImage.height;
  447. updateChanges.offset = IntVector2(position.x - (brushImageWidth / 2), position.y - (brushImageHeight / 2));
  448. if (updateChanges.offset.x < 0) updateChanges.offset.x = 0;
  449. if (updateChanges.offset.y < 0) updateChanges.offset.y = 0;
  450. IntRect boundsRect = IntRect(updateChanges.offset.x, updateChanges.offset.y, updateChanges.offset.x + brushImageWidth, updateChanges.offset.y + brushImageHeight);
  451. boundsRect = ClipIntRectToHeightmapBounds(terrainImage, boundsRect);
  452. updateChanges.oldImage = terrainImage.GetSubimage(boundsRect);
  453. // Iterate over the entire brush image
  454. for (int y = 0; y < brushImageHeight; ++y)
  455. {
  456. for (int x = 0; x < brushImageWidth; ++x)
  457. {
  458. Color brushColor = scaledSelectedBrushImage.GetPixel(x, y);
  459. // Only take opaque pixels into consideration for now
  460. if (brushColor.a == 0)
  461. continue;
  462. // Get the current terrain height at that position (centred to the brush's size)
  463. IntVector2 pos = IntVector2(position.x + x - (brushImageWidth / 2), position.y + y - (brushImageHeight / 2));
  464. // Make sure the pixel we're working on is atleast one pixel inside the terrainImage
  465. // as we need an adjacent pixel on all sides for the smoothing algorithm to work
  466. if (pos.x < 0 || pos.y < 0 || pos.x > terrainImage.width - 1 || pos.y > terrainImage.height - 1)
  467. continue;
  468. Color brp = terrainImage.GetPixel(pos.x + 1, pos.y + 1); // bottomRightPixel
  469. Color rp = terrainImage.GetPixel(pos.x + 1, pos.y); // rightPixel
  470. Color trp = terrainImage.GetPixel(pos.x + 1, pos.y - 1); // topRightPixel
  471. Color blp = terrainImage.GetPixel(pos.x - 1, pos.y + 1); // bottomLeftPixel
  472. Color lp = terrainImage.GetPixel(pos.x - 1, pos.y); // leftPixel
  473. Color tlp = terrainImage.GetPixel(pos.x - 1, pos.y - 1); // topLeftPixel
  474. Color bp = terrainImage.GetPixel(pos.x, pos.y + 1); // bottomPixel
  475. Color cp = terrainImage.GetPixel(pos.x, pos.y); // centerPixel
  476. Color tp = terrainImage.GetPixel(pos.x, pos.y - 1); // topPixel
  477. Color avgColor = Color(
  478. ((brp.r + rp.r + trp.r + blp.r + lp.r + tlp.r + bp.r + cp.r + tp.r) / 9),
  479. ((brp.g + rp.g + trp.g + blp.g + lp.g + tlp.g + bp.g + cp.g + tp.g) / 9),
  480. ((brp.b + rp.b + trp.b + blp.b + lp.b + tlp.b + bp.b + cp.b + tp.b) / 9)
  481. );
  482. Color newColor = Color(
  483. (Difference(cp.r, avgColor.r) * brushColor.a) + Smaller(cp.r, avgColor.r),
  484. (Difference(cp.g, avgColor.g) * brushColor.a) + Smaller(cp.g, avgColor.g),
  485. (Difference(cp.b, avgColor.b) * brushColor.a) + Smaller(cp.b, avgColor.b)
  486. );
  487. terrainImage.SetPixel(position.x + x - (brushImageWidth / 2), position.y + y - (brushImageHeight / 2), avgColor);
  488. }
  489. }
  490. updateChanges.newImage = terrainImage.GetSubimage(boundsRect);
  491. }
  492. private void UpdateTerrainSetHeight(Image@ terrainImage, IntVector2 position, TerrainEditorUpdateChanges@ updateChanges)
  493. {
  494. uint brushImageWidth = scaledSelectedBrushImage.width;
  495. uint brushImageHeight = scaledSelectedBrushImage.height;
  496. updateChanges.offset = IntVector2(position.x - (brushImageWidth / 2), position.y - (brushImageHeight / 2));
  497. if (updateChanges.offset.x < 0) updateChanges.offset.x = 0;
  498. if (updateChanges.offset.y < 0) updateChanges.offset.y = 0;
  499. IntRect boundsRect = IntRect(updateChanges.offset.x, updateChanges.offset.y, updateChanges.offset.x + brushImageWidth, updateChanges.offset.y + brushImageHeight);
  500. boundsRect = ClipIntRectToHeightmapBounds(terrainImage, boundsRect);
  501. updateChanges.oldImage = terrainImage.GetSubimage(boundsRect);
  502. float targetHeight = brushHeightSlider.value / 25;
  503. // Iterate over the entire brush image
  504. for (int y = 0; y < brushImageHeight; ++y)
  505. {
  506. for (int x = 0; x < brushImageWidth; ++x)
  507. {
  508. // Get the current terrain height at that position (centred to the brush's size)
  509. IntVector2 pos = IntVector2(position.x + x - (brushImageWidth / 2), position.y + y - (brushImageHeight / 2));
  510. Color newColor = terrainImage.GetPixel(pos.x, pos.y);
  511. Color brushColor = scaledSelectedBrushImage.GetPixel(x, y);
  512. // Ease the height to the target height (using the brush alpha as the 'speed'), making sure the alpha isn't 0
  513. newColor.r += (targetHeight - newColor.r) * brushColor.a;
  514. newColor.g += (targetHeight - newColor.g) * brushColor.a;
  515. newColor.b += (targetHeight - newColor.b) * brushColor.a;
  516. // Set it to target if its close enough
  517. if (Difference(targetHeight, newColor.r) < 0.01f) newColor.r = targetHeight;
  518. if (Difference(targetHeight, newColor.g) < 0.01f) newColor.g = targetHeight;
  519. if (Difference(targetHeight, newColor.b) < 0.01f) newColor.b = targetHeight;
  520. terrainImage.SetPixel(pos.x, pos.y, newColor);
  521. }
  522. }
  523. updateChanges.newImage = terrainImage.GetSubimage(boundsRect);
  524. }
  525. private void UpdateTerrainSetConstantHeight(Image@ terrainImage, float height)
  526. {
  527. height = Clamp(height, 0.0, 1.0);
  528. Color newColor = Color(height, height, height);
  529. // Iterate over the entire brush image
  530. for (int y = 0; y < terrainImage.height; ++y)
  531. {
  532. for (int x = 0; x < terrainImage.width; ++x)
  533. {
  534. terrainImage.SetPixel(x, y, newColor);
  535. }
  536. }
  537. }
  538. private IntRect ClipIntRectToHeightmapBounds(Image@ terrainImage, IntRect intRect) {
  539. if (intRect.left > terrainImage.width)
  540. intRect.left = terrainImage.width;
  541. if (intRect.right > terrainImage.width)
  542. intRect.right = terrainImage.width;
  543. if (intRect.top > terrainImage.height)
  544. intRect.top = terrainImage.height;
  545. if (intRect.bottom > terrainImage.height)
  546. intRect.bottom = terrainImage.height;
  547. return intRect;
  548. }
  549. }