propertyTabComponent.tsx 24 KB

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