| 106 | ######################################################################################################## |
| 107 | |
| 108 | def create_trainable(init, res=None, auto_mipmaps=True, min_max=None): |
| 109 | with torch.no_grad(): |
| 110 | if isinstance(init, Texture2D): |
| 111 | assert isinstance(init.data, torch.Tensor) |
| 112 | min_max = init.min_max if min_max is None else min_max |
| 113 | init = init.data |
| 114 | elif isinstance(init, np.ndarray): |
| 115 | init = torch.tensor(init, dtype=torch.float32, device='cuda') |
| 116 | |
| 117 | # Pad to NHWC if needed |
| 118 | if len(init.shape) == 1: # Extend constant to NHWC tensor |
| 119 | init = init[None, None, None, :] |
| 120 | elif len(init.shape) == 3: |
| 121 | init = init[None, ...] |
| 122 | |
| 123 | # Scale input to desired resolution. |
| 124 | if res is not None: |
| 125 | init = util.scale_img_nhwc(init, res) |
| 126 | |
| 127 | # Genreate custom mipchain |
| 128 | if not auto_mipmaps: |
| 129 | mip_chain = [init.clone().detach().requires_grad_(True)] |
| 130 | while mip_chain[-1].shape[1] > 1 or mip_chain[-1].shape[2] > 1: |
| 131 | new_size = [max(mip_chain[-1].shape[1] // 2, 1), max(mip_chain[-1].shape[2] // 2, 1)] |
| 132 | mip_chain += [util.scale_img_nhwc(mip_chain[-1], new_size)] |
| 133 | return Texture2D(mip_chain, min_max=min_max) |
| 134 | else: |
| 135 | return Texture2D(init, min_max=min_max) |
| 136 | |
| 137 | ######################################################################################################## |
| 138 | # Convert texture to and from SRGB |