propertyTabComponent.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. import { OptionsLineComponent } from '../../sharedComponents/optionsLineComponent';
  34. import { NodeMaterialModes } from 'babylonjs/Materials/Node/Enums/nodeMaterialModes';
  35. require("./propertyTab.scss");
  36. interface IPropertyTabComponentProps {
  37. globalState: GlobalState;
  38. }
  39. interface IPropertyTabComponentState {
  40. currentNode: Nullable<GraphNode>;
  41. currentFrame: Nullable<GraphFrame>;
  42. currentFrameNodePort: Nullable<FrameNodePort>;
  43. currentNodePort: Nullable<NodePort>;
  44. }
  45. export class PropertyTabComponent extends React.Component<IPropertyTabComponentProps, IPropertyTabComponentState> {
  46. private _onBuiltObserver: Nullable<Observer<void>>;
  47. private _modeSelect: React.RefObject<OptionsLineComponent>;
  48. constructor(props: IPropertyTabComponentProps) {
  49. super(props);
  50. this.state = { currentNode: null, currentFrame: null, currentFrameNodePort: null, currentNodePort: null };
  51. this._modeSelect = React.createRef();
  52. }
  53. componentDidMount() {
  54. this.props.globalState.onSelectionChangedObservable.add((selection) => {
  55. if (selection instanceof GraphNode) {
  56. this.setState({ currentNode: selection, currentFrame: null, currentFrameNodePort: null, currentNodePort: null });
  57. } else if (selection instanceof GraphFrame) {
  58. this.setState({ currentNode: null, currentFrame: selection, currentFrameNodePort: null, currentNodePort: null });
  59. } else if (isFramePortData(selection)) {
  60. this.setState({ currentNode: null, currentFrame: selection.frame, currentFrameNodePort: selection.port, currentNodePort: null });
  61. } else if (selection instanceof NodePort && selection.hasLabel()) {
  62. this.setState({ currentNode: null, currentFrame: null, currentFrameNodePort: null, currentNodePort: selection});
  63. } else {
  64. this.setState({ currentNode: null, currentFrame: null, currentFrameNodePort: null, currentNodePort: null });
  65. }
  66. });
  67. this._onBuiltObserver = this.props.globalState.onBuiltObservable.add(() => {
  68. this.forceUpdate();
  69. });
  70. }
  71. componentWillUnmount() {
  72. this.props.globalState.onBuiltObservable.remove(this._onBuiltObserver);
  73. }
  74. processInputBlockUpdate(ib: InputBlock) {
  75. this.props.globalState.onUpdateRequiredObservable.notifyObservers();
  76. if (ib.isConstant) {
  77. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  78. }
  79. }
  80. renderInputBlock(block: InputBlock) {
  81. switch (block.type) {
  82. case NodeMaterialBlockConnectionPointTypes.Float:
  83. let cantDisplaySlider = (isNaN(block.min) || isNaN(block.max) || block.min === block.max);
  84. return (
  85. <div key={block.uniqueId} >
  86. {
  87. block.isBoolean &&
  88. <CheckBoxLineComponent key={block.uniqueId} label={block.name} target={block} propertyName="value"
  89. onValueChanged={() => {
  90. this.processInputBlockUpdate(block);
  91. }}/>
  92. }
  93. {
  94. !block.isBoolean && cantDisplaySlider &&
  95. <FloatLineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block} propertyName="value"
  96. onChange={() => this.processInputBlockUpdate(block)}/>
  97. }
  98. {
  99. !block.isBoolean && !cantDisplaySlider &&
  100. <SliderLineComponent key={block.uniqueId} label={block.name} target={block} propertyName="value"
  101. step={(block.max - block.min) / 100.0} minimum={block.min} maximum={block.max}
  102. onChange={() => this.processInputBlockUpdate(block)}/>
  103. }
  104. </div>
  105. );
  106. case NodeMaterialBlockConnectionPointTypes.Color3:
  107. return (
  108. <Color3LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  109. propertyName="value"
  110. onChange={() => this.processInputBlockUpdate(block)}
  111. />
  112. );
  113. case NodeMaterialBlockConnectionPointTypes.Color4:
  114. return (
  115. <Color4LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block} propertyName="value"
  116. onChange={() => this.processInputBlockUpdate(block)}/>
  117. );
  118. case NodeMaterialBlockConnectionPointTypes.Vector2:
  119. return (
  120. <Vector2LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  121. propertyName="value"
  122. onChange={() => this.processInputBlockUpdate(block)}/>
  123. );
  124. case NodeMaterialBlockConnectionPointTypes.Vector3:
  125. return (
  126. <Vector3LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  127. propertyName="value"
  128. onChange={() => this.processInputBlockUpdate(block)}/>
  129. );
  130. case NodeMaterialBlockConnectionPointTypes.Vector4:
  131. return (
  132. <Vector4LineComponent globalState={this.props.globalState} key={block.uniqueId} label={block.name} target={block}
  133. propertyName="value"
  134. onChange={() => this.processInputBlockUpdate(block)}/>
  135. );
  136. }
  137. return null;
  138. }
  139. load(file: File) {
  140. Tools.ReadFile(file, (data) => {
  141. let decoder = new TextDecoder("utf-8");
  142. SerializationTools.Deserialize(JSON.parse(decoder.decode(data)), this.props.globalState);
  143. this.changeMode(this.props.globalState.nodeMaterial!.mode, true, false);
  144. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  145. }, undefined, true);
  146. }
  147. save() {
  148. let json = SerializationTools.Serialize(this.props.globalState.nodeMaterial, this.props.globalState);
  149. StringTools.DownloadAsFile(this.props.globalState.hostDocument, json, "nodeMaterial.json");
  150. }
  151. customSave() {
  152. this.props.globalState.onLogRequiredObservable.notifyObservers({message: "Saving your material to Babylon.js snippet server...", isError: false});
  153. this.props.globalState.customSave!.action(SerializationTools.Serialize(this.props.globalState.nodeMaterial, this.props.globalState)).then(() => {
  154. this.props.globalState.onLogRequiredObservable.notifyObservers({message: "Material saved successfully", isError: false});
  155. }).catch((err) => {
  156. this.props.globalState.onLogRequiredObservable.notifyObservers({message: err, isError: true});
  157. });
  158. }
  159. saveToSnippetServer() {
  160. const material = this.props.globalState.nodeMaterial;
  161. const xmlHttp = new XMLHttpRequest();
  162. let json = SerializationTools.Serialize(material, this.props.globalState);
  163. xmlHttp.onreadystatechange = () => {
  164. if (xmlHttp.readyState == 4) {
  165. if (xmlHttp.status == 200) {
  166. var snippet = JSON.parse(xmlHttp.responseText);
  167. const oldId = material.snippetId;
  168. material.snippetId = snippet.id;
  169. if (snippet.version && snippet.version != "0") {
  170. material.snippetId += "#" + snippet.version;
  171. }
  172. this.forceUpdate();
  173. if (navigator.clipboard) {
  174. navigator.clipboard.writeText(material.snippetId);
  175. }
  176. let windowAsAny = window as any;
  177. if (windowAsAny.Playground && oldId) {
  178. windowAsAny.Playground.onRequestCodeChangeObservable.notifyObservers({
  179. regex: new RegExp(oldId, "g"),
  180. replace: material.snippetId
  181. });
  182. }
  183. alert("NodeMaterial saved with ID: " + material.snippetId + " (please note that the id was also saved to your clipboard)");
  184. }
  185. else {
  186. 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.`);
  187. }
  188. }
  189. };
  190. xmlHttp.open("POST", NodeMaterial.SnippetUrl + (material.snippetId ? "/" + material.snippetId : ""), true);
  191. xmlHttp.setRequestHeader("Content-Type", "application/json");
  192. var dataToSend = {
  193. payload : JSON.stringify({
  194. nodeMaterial: json
  195. }),
  196. name: "",
  197. description: "",
  198. tags: ""
  199. };
  200. xmlHttp.send(JSON.stringify(dataToSend));
  201. }
  202. loadFromSnippet() {
  203. const material = this.props.globalState.nodeMaterial;
  204. const scene = material.getScene();
  205. let snippedID = window.prompt("Please enter the snippet ID to use");
  206. if (!snippedID) {
  207. return;
  208. }
  209. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  210. NodeMaterial.ParseFromSnippetAsync(snippedID, scene, "", material).then(() => {
  211. material.build();
  212. this.props.globalState.onResetRequiredObservable.notifyObservers();
  213. }).catch((err) => {
  214. alert("Unable to load your node material: " + err);
  215. });
  216. }
  217. changeMode(value: any, force = false, loadDefault = true) {
  218. if (this.props.globalState.mode === value) {
  219. return;
  220. }
  221. if (!force && !confirm('Are your sure? You will loose your current changes (if any) if they are not saved!')) {
  222. this._modeSelect.current?.setValue(this.props.globalState.mode);
  223. return;
  224. }
  225. if (force) {
  226. this._modeSelect.current?.setValue(value);
  227. }
  228. this.props.globalState.mode = value as NodeMaterialModes;
  229. if (loadDefault) {
  230. switch (value) {
  231. case NodeMaterialModes.Material:
  232. this.props.globalState.nodeMaterial!.setToDefault();
  233. this.props.globalState.onResetRequiredObservable.notifyObservers();
  234. break;
  235. case NodeMaterialModes.PostProcess:
  236. this.props.globalState.nodeMaterial!.setToDefaultPostProcess();
  237. this.props.globalState.onResetRequiredObservable.notifyObservers();
  238. break;
  239. }
  240. }
  241. window.dispatchEvent(new CustomEvent('nme_refresh'));
  242. }
  243. render() {
  244. if (this.state.currentNode) {
  245. return (
  246. <div id="propertyTab">
  247. <div id="header">
  248. <img id="logo" src="https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png" />
  249. <div id="title">
  250. NODE MATERIAL EDITOR
  251. </div>
  252. </div>
  253. {this.state.currentNode?.renderProperties() || this.state.currentNodePort?.node.renderProperties()}
  254. </div>
  255. );
  256. }
  257. if (this.state.currentFrameNodePort && this.state.currentFrame) {
  258. return (
  259. <FrameNodePortPropertyTabComponent globalState={this.props.globalState} frame={this.state.currentFrame} frameNodePort={this.state.currentFrameNodePort}/>
  260. );
  261. }
  262. if (this.state.currentNodePort) {
  263. return (
  264. <NodePortPropertyTabComponent globalState={this.props.globalState} nodePort={this.state.currentNodePort}/>
  265. );
  266. }
  267. if (this.state.currentFrame) {
  268. return (
  269. <FramePropertyTabComponent globalState={this.props.globalState} frame={this.state.currentFrame}/>
  270. );
  271. }
  272. let gridSize = DataStorage.ReadNumber("GridSize", 20);
  273. return (
  274. <div id="propertyTab">
  275. <div id="header">
  276. <img id="logo" src="https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png" />
  277. <div id="title">
  278. NODE MATERIAL EDITOR
  279. </div>
  280. </div>
  281. <div>
  282. <LineContainerComponent title="MODE">
  283. <OptionsLineComponent ref={this._modeSelect} label="Mode" target={this} getSelection={(target) => this.props.globalState.mode} options={[{ label: "Material", value: NodeMaterialModes.Material }, { label: "Post Process", value: NodeMaterialModes.PostProcess }]} onSelect={(value) => this.changeMode(value)} />
  284. </LineContainerComponent>
  285. <LineContainerComponent title="GENERAL">
  286. <TextLineComponent label="Version" value={Engine.Version}/>
  287. <TextLineComponent label="Help" value="doc.babylonjs.com" underline={true} onLink={() => window.open('https://doc.babylonjs.com/how_to/node_material', '_blank')}/>
  288. <ButtonLineComponent label="Reset to default" onClick={() => {
  289. this.props.globalState.nodeMaterial!.setToDefault();
  290. this.props.globalState.onResetRequiredObservable.notifyObservers();
  291. }} />
  292. </LineContainerComponent>
  293. <LineContainerComponent title="UI">
  294. <ButtonLineComponent label="Zoom to fit" onClick={() => {
  295. this.props.globalState.onZoomToFitRequiredObservable.notifyObservers();
  296. }} />
  297. <ButtonLineComponent label="Reorganize" onClick={() => {
  298. this.props.globalState.onReOrganizedRequiredObservable.notifyObservers();
  299. }} />
  300. </LineContainerComponent>
  301. <LineContainerComponent title="OPTIONS">
  302. <CheckBoxLineComponent label="Embed textures when saving"
  303. isSelected={() => DataStorage.ReadBoolean("EmbedTextures", true)}
  304. onSelect={(value: boolean) => {
  305. DataStorage.WriteBoolean("EmbedTextures", value);
  306. }}
  307. />
  308. <SliderLineComponent label="Grid size" minimum={0} maximum={100} step={5}
  309. decimalCount={0}
  310. directValue={gridSize}
  311. onChange={(value) => {
  312. DataStorage.WriteNumber("GridSize", value);
  313. this.props.globalState.onGridSizeChanged.notifyObservers();
  314. this.forceUpdate();
  315. }}
  316. />
  317. <CheckBoxLineComponent label="Show grid"
  318. isSelected={() => DataStorage.ReadBoolean("ShowGrid", true)}
  319. onSelect={(value: boolean) => {
  320. DataStorage.WriteBoolean("ShowGrid", value);
  321. this.props.globalState.onGridSizeChanged.notifyObservers();
  322. }}
  323. />
  324. </LineContainerComponent>
  325. <LineContainerComponent title="FILE">
  326. <FileButtonLineComponent label="Load" onClick={(file) => this.load(file)} accept=".json" />
  327. <ButtonLineComponent label="Save" onClick={() => {
  328. this.save();
  329. }} />
  330. <ButtonLineComponent label="Generate code" onClick={() => {
  331. StringTools.DownloadAsFile(this.props.globalState.hostDocument, this.props.globalState.nodeMaterial!.generateCode(), "code.txt");
  332. }} />
  333. <ButtonLineComponent label="Export shaders" onClick={() => {
  334. StringTools.DownloadAsFile(this.props.globalState.hostDocument, this.props.globalState.nodeMaterial!.compiledShaders, "shaders.txt");
  335. }} />
  336. {
  337. this.props.globalState.customSave &&
  338. <ButtonLineComponent label={this.props.globalState.customSave!.label} onClick={() => {
  339. this.customSave();
  340. }} />
  341. }
  342. </LineContainerComponent>
  343. {
  344. !this.props.globalState.customSave &&
  345. <LineContainerComponent title="SNIPPET">
  346. {
  347. this.props.globalState.nodeMaterial!.snippetId &&
  348. <TextLineComponent label="Snippet ID" value={this.props.globalState.nodeMaterial!.snippetId} />
  349. }
  350. <ButtonLineComponent label="Load from snippet server" onClick={() => this.loadFromSnippet()} />
  351. <ButtonLineComponent label="Save to snippet server" onClick={() => {
  352. this.saveToSnippetServer();
  353. }} />
  354. </LineContainerComponent>
  355. }
  356. <LineContainerComponent title="INPUTS">
  357. {
  358. this.props.globalState.nodeMaterial.getInputBlocks().map((ib) => {
  359. if (!ib.isUniform || ib.isSystemValue || !ib.name) {
  360. return null;
  361. }
  362. return this.renderInputBlock(ib);
  363. })
  364. }
  365. </LineContainerComponent>
  366. </div>
  367. </div>
  368. );
  369. }
  370. }