propertyTabComponent.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. }
  253. }
  254. switch (value) {
  255. case NodeMaterialModes.Material:
  256. this.props.globalState.previewType = PreviewType.Sphere;
  257. break;
  258. case NodeMaterialModes.Particle:
  259. this.props.globalState.previewType = PreviewType.Bubbles;
  260. break;
  261. }
  262. this.props.globalState.listOfCustomPreviewFiles = [];
  263. (this.props.globalState.previewFile as any) = undefined;
  264. DataStorage.WriteNumber("PreviewType", this.props.globalState.previewType);
  265. this.props.globalState.mode = value as NodeMaterialModes;
  266. this.props.globalState.onResetRequiredObservable.notifyObservers();
  267. return true;
  268. }
  269. render() {
  270. if (this.state.currentNode) {
  271. return (
  272. <div id="propertyTab">
  273. <div id="header">
  274. <img id="logo" src="https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png" />
  275. <div id="title">
  276. NODE MATERIAL EDITOR
  277. </div>
  278. </div>
  279. {this.state.currentNode?.renderProperties() || this.state.currentNodePort?.node.renderProperties()}
  280. </div>
  281. );
  282. }
  283. if (this.state.currentFrameNodePort && this.state.currentFrame) {
  284. return (
  285. <FrameNodePortPropertyTabComponent globalState={this.props.globalState} frame={this.state.currentFrame} frameNodePort={this.state.currentFrameNodePort}/>
  286. );
  287. }
  288. if (this.state.currentNodePort) {
  289. return (
  290. <NodePortPropertyTabComponent globalState={this.props.globalState} nodePort={this.state.currentNodePort}/>
  291. );
  292. }
  293. if (this.state.currentFrame) {
  294. return (
  295. <FramePropertyTabComponent globalState={this.props.globalState} frame={this.state.currentFrame}/>
  296. );
  297. }
  298. let gridSize = DataStorage.ReadNumber("GridSize", 20);
  299. const modeList = [
  300. { label: "Material", value: NodeMaterialModes.Material },
  301. { label: "Post Process", value: NodeMaterialModes.PostProcess },
  302. { label: "Particle", value: NodeMaterialModes.Particle },
  303. ];
  304. return (
  305. <div id="propertyTab">
  306. <div id="header">
  307. <img id="logo" src="https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png" />
  308. <div id="title">
  309. NODE MATERIAL EDITOR
  310. </div>
  311. </div>
  312. <div>
  313. <LineContainerComponent title="GENERAL">
  314. <OptionsLineComponent ref={this._modeSelect} label="Mode" target={this} getSelection={(target) => this.props.globalState.mode} options={modeList} onSelect={(value) => this.changeMode(value)} />
  315. <TextLineComponent label="Version" value={Engine.Version}/>
  316. <TextLineComponent label="Help" value="doc.babylonjs.com" underline={true} onLink={() => window.open('https://doc.babylonjs.com/how_to/node_material', '_blank')}/>
  317. <ButtonLineComponent label="Reset to default" onClick={() => {
  318. this.props.globalState.nodeMaterial!.setToDefault();
  319. this.props.globalState.onResetRequiredObservable.notifyObservers();
  320. }} />
  321. </LineContainerComponent>
  322. <LineContainerComponent title="UI">
  323. <ButtonLineComponent label="Zoom to fit" onClick={() => {
  324. this.props.globalState.onZoomToFitRequiredObservable.notifyObservers();
  325. }} />
  326. <ButtonLineComponent label="Reorganize" onClick={() => {
  327. this.props.globalState.onReOrganizedRequiredObservable.notifyObservers();
  328. }} />
  329. </LineContainerComponent>
  330. <LineContainerComponent title="OPTIONS">
  331. <CheckBoxLineComponent label="Embed textures when saving"
  332. isSelected={() => DataStorage.ReadBoolean("EmbedTextures", true)}
  333. onSelect={(value: boolean) => {
  334. DataStorage.WriteBoolean("EmbedTextures", value);
  335. }}
  336. />
  337. <SliderLineComponent label="Grid size" minimum={0} maximum={100} step={5}
  338. decimalCount={0}
  339. directValue={gridSize}
  340. onChange={(value) => {
  341. DataStorage.WriteNumber("GridSize", value);
  342. this.props.globalState.onGridSizeChanged.notifyObservers();
  343. this.forceUpdate();
  344. }}
  345. />
  346. <CheckBoxLineComponent label="Show grid"
  347. isSelected={() => DataStorage.ReadBoolean("ShowGrid", true)}
  348. onSelect={(value: boolean) => {
  349. DataStorage.WriteBoolean("ShowGrid", value);
  350. this.props.globalState.onGridSizeChanged.notifyObservers();
  351. }}
  352. />
  353. </LineContainerComponent>
  354. <LineContainerComponent title="FILE">
  355. <FileButtonLineComponent label="Load" onClick={(file) => this.load(file)} accept=".json" />
  356. <ButtonLineComponent label="Save" onClick={() => {
  357. this.save();
  358. }} />
  359. <ButtonLineComponent label="Generate code" onClick={() => {
  360. StringTools.DownloadAsFile(this.props.globalState.hostDocument, this.props.globalState.nodeMaterial!.generateCode(), "code.txt");
  361. }} />
  362. <ButtonLineComponent label="Export shaders" onClick={() => {
  363. StringTools.DownloadAsFile(this.props.globalState.hostDocument, this.props.globalState.nodeMaterial!.compiledShaders, "shaders.txt");
  364. }} />
  365. {
  366. this.props.globalState.customSave &&
  367. <ButtonLineComponent label={this.props.globalState.customSave!.label} onClick={() => {
  368. this.customSave();
  369. }} />
  370. }
  371. <FileButtonLineComponent label="Load Frame" uploadName={'frame-upload'} onClick={(file) => this.loadFrame(file)} accept=".json" />
  372. </LineContainerComponent>
  373. {
  374. !this.props.globalState.customSave &&
  375. <LineContainerComponent title="SNIPPET">
  376. {
  377. this.props.globalState.nodeMaterial!.snippetId &&
  378. <TextLineComponent label="Snippet ID" value={this.props.globalState.nodeMaterial!.snippetId} />
  379. }
  380. <ButtonLineComponent label="Load from snippet server" onClick={() => this.loadFromSnippet()} />
  381. <ButtonLineComponent label="Save to snippet server" onClick={() => {
  382. this.saveToSnippetServer();
  383. }} />
  384. </LineContainerComponent>
  385. }
  386. <LineContainerComponent title="INPUTS">
  387. {
  388. this.props.globalState.nodeMaterial.getInputBlocks().map((ib) => {
  389. if (!ib.isUniform || ib.isSystemValue || !ib.name) {
  390. return null;
  391. }
  392. return this.renderInputBlock(ib);
  393. })
  394. }
  395. </LineContainerComponent>
  396. </div>
  397. </div>
  398. );
  399. }
  400. }