propertyTabComponent.tsx 23 KB

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