propertyTabComponent.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import * as React from "react";
  2. import { GlobalState } from '../../globalState';
  3. import { Nullable } from 'babylonjs/types';
  4. import { ButtonLineComponent } from '../../sharedComponents/buttonLineComponent';
  5. import { LineContainerComponent } from '../../sharedComponents/lineContainerComponent';
  6. import { StringTools } from '../../stringTools';
  7. import { FileButtonLineComponent } from '../../sharedComponents/fileButtonLineComponent';
  8. import { Tools } from 'babylonjs/Misc/tools';
  9. import { SerializationTools } from '../../serializationTools';
  10. import { CheckBoxLineComponent } from '../../sharedComponents/checkBoxLineComponent';
  11. import { DataStorage } from 'babylonjs/Misc/dataStorage';
  12. import { GraphNode } from '../../diagram/graphNode';
  13. import { SliderLineComponent } from '../../sharedComponents/sliderLineComponent';
  14. import { GraphFrame } from '../../diagram/graphFrame';
  15. import { TextLineComponent } from '../../sharedComponents/textLineComponent';
  16. import { Engine } from 'babylonjs/Engines/engine';
  17. import { FramePropertyTabComponent } from '../../diagram/properties/framePropertyComponent';
  18. import { FrameNodePortPropertyTabComponent } from '../../diagram/properties/frameNodePortPropertyComponent';
  19. import { NodePortPropertyTabComponent } from '../../diagram/properties/nodePortPropertyComponent';
  20. import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock';
  21. import { NodeMaterialBlockConnectionPointTypes } from 'babylonjs/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes';
  22. import { Color3LineComponent } from '../../sharedComponents/color3LineComponent';
  23. import { FloatLineComponent } from '../../sharedComponents/floatLineComponent';
  24. import { Color4LineComponent } from '../../sharedComponents/color4LineComponent';
  25. import { Vector2LineComponent } from '../../sharedComponents/vector2LineComponent';
  26. import { Vector3LineComponent } from '../../sharedComponents/vector3LineComponent';
  27. import { Vector4LineComponent } from '../../sharedComponents/vector4LineComponent';
  28. import { Observer } from 'babylonjs/Misc/observable';
  29. import { NodeMaterial } from 'babylonjs/Materials/Node/nodeMaterial';
  30. import { FrameNodePort } from '../../diagram/frameNodePort';
  31. import { NodePort } from '../../diagram/nodePort';
  32. import { isFramePortData } from '../../diagram/graphCanvas';
  33. require("./propertyTab.scss");
  34. interface IPropertyTabComponentProps {
  35. globalState: GlobalState;
  36. }
  37. interface IPropertyTabComponentState {
  38. currentNode: Nullable<GraphNode>,
  39. currentFrame: Nullable<GraphFrame>,
  40. currentFrameNodePort: Nullable<FrameNodePort>,
  41. currentNodePort: Nullable<NodePort>
  42. }
  43. export class PropertyTabComponent extends React.Component<IPropertyTabComponentProps, IPropertyTabComponentState> {
  44. private _onBuiltObserver: Nullable<Observer<void>>;
  45. constructor(props: IPropertyTabComponentProps) {
  46. super(props)
  47. this.state = { currentNode: null, currentFrame: null, currentFrameNodePort: null, currentNodePort: null };
  48. }
  49. componentDidMount() {
  50. this.props.globalState.onSelectionChangedObservable.add(selection => {
  51. if (selection instanceof GraphNode) {
  52. this.setState({ currentNode: selection, currentFrame: null, currentFrameNodePort: null, currentNodePort: null });
  53. } else if (selection instanceof GraphFrame) {
  54. this.setState({ currentNode: null, currentFrame: selection, currentFrameNodePort: null, currentNodePort: null });
  55. } else if(isFramePortData(selection)) {
  56. this.setState({ currentNode: null, currentFrame: selection.frame, currentFrameNodePort: selection.port, currentNodePort: null });
  57. } else if (selection instanceof NodePort && selection.hasLabel()) {
  58. this.setState({ currentNode: null, currentFrame: null, currentFrameNodePort: null, currentNodePort: selection})
  59. } else {
  60. this.setState({ currentNode: null, currentFrame: null, currentFrameNodePort: null, currentNodePort: null });
  61. }
  62. });
  63. this._onBuiltObserver = this.props.globalState.onBuiltObservable.add(() => {
  64. this.forceUpdate();
  65. });
  66. }
  67. componentWillUnmount() {
  68. this.props.globalState.onBuiltObservable.remove(this._onBuiltObserver);
  69. }
  70. processInputBlockUpdate(ib: InputBlock) {
  71. this.props.globalState.onUpdateRequiredObservable.notifyObservers();
  72. if (ib.isConstant) {
  73. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  74. }
  75. }
  76. renderInputBlock(block: InputBlock) {
  77. switch (block.type) {
  78. case NodeMaterialBlockConnectionPointTypes.Float:
  79. let cantDisplaySlider = (isNaN(block.min) || isNaN(block.max) || block.min === block.max);
  80. return (
  81. <div key={block.uniqueId} >
  82. {
  83. block.isBoolean &&
  84. <CheckBoxLineComponent key={block.uniqueId} label={block.name} target={block} propertyName="value"
  85. onValueChanged={() => {
  86. this.processInputBlockUpdate(block);
  87. }}/>
  88. }
  89. {
  90. !block.isBoolean && cantDisplaySlider &&
  91. <FloatLineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block} propertyName="value"
  92. onChange={() => this.processInputBlockUpdate(block)}/>
  93. }
  94. {
  95. !block.isBoolean && !cantDisplaySlider &&
  96. <SliderLineComponent key={block.uniqueId} label={block.name} target={block} propertyName="value"
  97. step={(block.max - block.min) / 100.0} minimum={block.min} maximum={block.max}
  98. onChange={() => this.processInputBlockUpdate(block)}/>
  99. }
  100. </div>
  101. );
  102. case NodeMaterialBlockConnectionPointTypes.Color3:
  103. return (
  104. <Color3LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  105. propertyName="value"
  106. onChange={() => this.processInputBlockUpdate(block)}
  107. />
  108. )
  109. case NodeMaterialBlockConnectionPointTypes.Color4:
  110. return (
  111. <Color4LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block} propertyName="value"
  112. onChange={() => this.processInputBlockUpdate(block)}/>
  113. )
  114. case NodeMaterialBlockConnectionPointTypes.Vector2:
  115. return (
  116. <Vector2LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  117. propertyName="value"
  118. onChange={() => this.processInputBlockUpdate(block)}/>
  119. )
  120. case NodeMaterialBlockConnectionPointTypes.Vector3:
  121. return (
  122. <Vector3LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  123. propertyName="value"
  124. onChange={() => this.processInputBlockUpdate(block)}/>
  125. )
  126. case NodeMaterialBlockConnectionPointTypes.Vector4:
  127. return (
  128. <Vector4LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  129. propertyName="value"
  130. onChange={() => this.processInputBlockUpdate(block)}/>
  131. )
  132. }
  133. return null;
  134. }
  135. load(file: File) {
  136. Tools.ReadFile(file, (data) => {
  137. let decoder = new TextDecoder("utf-8");
  138. SerializationTools.Deserialize(JSON.parse(decoder.decode(data)), this.props.globalState);
  139. }, undefined, true);
  140. }
  141. save() {
  142. let json = SerializationTools.Serialize(this.props.globalState.nodeMaterial, this.props.globalState);
  143. StringTools.DownloadAsFile(this.props.globalState.hostDocument, json, "nodeMaterial.json");
  144. }
  145. customSave() {
  146. this.props.globalState.onLogRequiredObservable.notifyObservers({message: "Saving your material to Babylon.js snippet server...", isError: false});
  147. this.props.globalState.customSave!.action(SerializationTools.Serialize(this.props.globalState.nodeMaterial, this.props.globalState)).then(() => {
  148. this.props.globalState.onLogRequiredObservable.notifyObservers({message: "Material saved successfully", isError: false});
  149. }).catch(err => {
  150. this.props.globalState.onLogRequiredObservable.notifyObservers({message: err, isError: true});
  151. });
  152. }
  153. saveToSnippetServer() {
  154. const material = this.props.globalState.nodeMaterial;
  155. const xmlHttp = new XMLHttpRequest();
  156. let json = SerializationTools.Serialize(material, this.props.globalState);
  157. xmlHttp.onreadystatechange = () => {
  158. if (xmlHttp.readyState == 4) {
  159. if (xmlHttp.status == 200) {
  160. var snippet = JSON.parse(xmlHttp.responseText);
  161. const oldId = material.snippetId;
  162. material.snippetId = snippet.id;
  163. if (snippet.version && snippet.version != "0") {
  164. material.snippetId += "#" + snippet.version;
  165. }
  166. this.forceUpdate();
  167. if (navigator.clipboard) {
  168. navigator.clipboard.writeText(material.snippetId);
  169. }
  170. let windowAsAny = window as any;
  171. if (windowAsAny.Playground && oldId) {
  172. windowAsAny.Playground.onRequestCodeChangeObservable.notifyObservers({
  173. regex: new RegExp(oldId, "g"),
  174. replace: material.snippetId
  175. });
  176. }
  177. alert("NodeMaterial saved with ID: " + material.snippetId + " (please note that the id was also saved to your clipboard)");
  178. }
  179. else {
  180. alert(`Unable to save your node material. It may be too large (${(dataToSend.payload.length / 1024).toFixed(2)} KB) because of embedded textures. Please reduce texture sizes or point to a specific url instead of embedding them and try again.`);
  181. }
  182. }
  183. }
  184. xmlHttp.open("POST", NodeMaterial.SnippetUrl + (material.snippetId ? "/" + material.snippetId : ""), true);
  185. xmlHttp.setRequestHeader("Content-Type", "application/json");
  186. var dataToSend = {
  187. payload : JSON.stringify({
  188. nodeMaterial: json
  189. }),
  190. name: "",
  191. description: "",
  192. tags: ""
  193. };
  194. xmlHttp.send(JSON.stringify(dataToSend));
  195. }
  196. loadFromSnippet() {
  197. const material = this.props.globalState.nodeMaterial;
  198. const scene = material.getScene();
  199. let snippedID = window.prompt("Please enter the snippet ID to use");
  200. if (!snippedID) {
  201. return;
  202. }
  203. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  204. NodeMaterial.ParseFromSnippetAsync(snippedID, scene, "", material).then(() => {
  205. material.build();
  206. this.props.globalState.onResetRequiredObservable.notifyObservers();
  207. }).catch(err => {
  208. alert("Unable to load your node material: " + err);
  209. });
  210. }
  211. render() {
  212. if (this.state.currentNode) {
  213. return (
  214. <div id="propertyTab">
  215. <div id="header">
  216. <img id="logo" src="https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png" />
  217. <div id="title">
  218. NODE MATERIAL EDITOR
  219. </div>
  220. </div>
  221. {this.state.currentNode?.renderProperties() || this.state.currentNodePort?.node.renderProperties()}
  222. </div>
  223. );
  224. }
  225. if (this.state.currentFrameNodePort && this.state.currentFrame) {
  226. return (
  227. <FrameNodePortPropertyTabComponent globalState={this.props.globalState} frame={this.state.currentFrame} frameNodePort={this.state.currentFrameNodePort}/>
  228. );
  229. }
  230. if (this.state.currentNodePort) {
  231. return (
  232. <NodePortPropertyTabComponent globalState={this.props.globalState} nodePort={this.state.currentNodePort}/>
  233. );
  234. }
  235. if (this.state.currentFrame) {
  236. return (
  237. <FramePropertyTabComponent globalState={this.props.globalState} frame={this.state.currentFrame}/>
  238. );
  239. }
  240. let gridSize = DataStorage.ReadNumber("GridSize", 20);
  241. return (
  242. <div id="propertyTab">
  243. <div id="header">
  244. <img id="logo" src="https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png" />
  245. <div id="title">
  246. NODE MATERIAL EDITOR
  247. </div>
  248. </div>
  249. <div>
  250. <LineContainerComponent title="GENERAL">
  251. <TextLineComponent label="Version" value={Engine.Version}/>
  252. <TextLineComponent label="Help" value="doc.babylonjs.com" underline={true} onLink={() => window.open('https://doc.babylonjs.com/how_to/node_material', '_blank')}/>
  253. <ButtonLineComponent label="Reset to default" onClick={() => {
  254. this.props.globalState.nodeMaterial!.setToDefault();
  255. this.props.globalState.onResetRequiredObservable.notifyObservers();
  256. }} />
  257. </LineContainerComponent>
  258. <LineContainerComponent title="UI">
  259. <ButtonLineComponent label="Zoom to fit" onClick={() => {
  260. this.props.globalState.onZoomToFitRequiredObservable.notifyObservers();
  261. }} />
  262. <ButtonLineComponent label="Reorganize" onClick={() => {
  263. this.props.globalState.onReOrganizedRequiredObservable.notifyObservers();
  264. }} />
  265. </LineContainerComponent>
  266. <LineContainerComponent title="OPTIONS">
  267. <CheckBoxLineComponent label="Embed textures when saving"
  268. isSelected={() => DataStorage.ReadBoolean("EmbedTextures", true)}
  269. onSelect={(value: boolean) => {
  270. DataStorage.WriteBoolean("EmbedTextures", value);
  271. }}
  272. />
  273. <SliderLineComponent label="Grid size" minimum={0} maximum={100} step={5}
  274. decimalCount={0}
  275. directValue={gridSize}
  276. onChange={value => {
  277. DataStorage.WriteNumber("GridSize", value);
  278. this.props.globalState.onGridSizeChanged.notifyObservers();
  279. this.forceUpdate();
  280. }}
  281. />
  282. <CheckBoxLineComponent label="Show grid"
  283. isSelected={() => DataStorage.ReadBoolean("ShowGrid", true)}
  284. onSelect={(value: boolean) => {
  285. DataStorage.WriteBoolean("ShowGrid", value);
  286. this.props.globalState.onGridSizeChanged.notifyObservers();
  287. }}
  288. />
  289. </LineContainerComponent>
  290. <LineContainerComponent title="FILE">
  291. <FileButtonLineComponent label="Load" onClick={(file) => this.load(file)} accept=".json" />
  292. <ButtonLineComponent label="Save" onClick={() => {
  293. this.save();
  294. }} />
  295. <ButtonLineComponent label="Generate code" onClick={() => {
  296. StringTools.DownloadAsFile(this.props.globalState.hostDocument, this.props.globalState.nodeMaterial!.generateCode(), "code.txt");
  297. }} />
  298. <ButtonLineComponent label="Export shaders" onClick={() => {
  299. StringTools.DownloadAsFile(this.props.globalState.hostDocument, this.props.globalState.nodeMaterial!.compiledShaders, "shaders.txt");
  300. }} />
  301. {
  302. this.props.globalState.customSave &&
  303. <ButtonLineComponent label={this.props.globalState.customSave!.label} onClick={() => {
  304. this.customSave();
  305. }} />
  306. }
  307. </LineContainerComponent>
  308. {
  309. !this.props.globalState.customSave &&
  310. <LineContainerComponent title="SNIPPET">
  311. {
  312. this.props.globalState.nodeMaterial!.snippetId &&
  313. <TextLineComponent label="Snippet ID" value={this.props.globalState.nodeMaterial!.snippetId} />
  314. }
  315. <ButtonLineComponent label="Load from snippet server" onClick={() => this.loadFromSnippet()} />
  316. <ButtonLineComponent label="Save to snippet server" onClick={() => {
  317. this.saveToSnippetServer();
  318. }} />
  319. </LineContainerComponent>
  320. }
  321. <LineContainerComponent title="INPUTS">
  322. {
  323. this.props.globalState.nodeMaterial.getInputBlocks().map(ib => {
  324. if (!ib.isUniform || ib.isSystemValue || !ib.name) {
  325. return null;
  326. }
  327. return this.renderInputBlock(ib);
  328. })
  329. }
  330. </LineContainerComponent>
  331. </div>
  332. </div>
  333. );
  334. }
  335. }