Author: Nako

[Trouble Shooting] Where is “Shader to RGB” Node in Blender?

This is a problem I am stuck on, but it is easy to solve.

Problem

I was finding the shade node “Shader to RGB” that converts the output color of a shade into RGB. However I couldn’t find it in Blender 8.3.

Solution

“Shader to RGB” node is prepared for “EEVEE” renderer only. So we need to change the Render Engine into “EEVEE” and we can find “Shader to RGB” in Add > Converter.

[Tips] “Set Inverse” for “Child Of” Constraint using Blender Python

This is a trouble shooting for using bpy.ops.constraint.childof_set_inverse.

Trouble

When I tried to set “Set Inverse” for “Child Of” constraint in bone and executed bpy.ops.constraint.childof_set_inverse(constraint=”Child Of”, owner=’BONE’) on Blender, the following error occurred. How can we solve it?

>>> bpy.ops.constraint.childof_set_inverse(constraint="Child Of", owner='BONE')
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
  File "C:\Program Files\Blender Foundation\Blender 2.83\2.83\scripts\modules\bpy\ops.py", line 201, in __call__
    ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.constraint.childof_set_inverse.poll() Context missing 'constraint'

Environment

Windows 10
Blender 2.83

Solution

To execute this operation, we should pass the context that contains target constraint and activate the target bone in pose mode.

import bpy

bone_name = "foot.IK.L"
bpy.ops.object.mode_set(mode='POSE', toggle=False)
pose_bone = bpy.context.active_object.pose.bones[bone_name]

# set the target constraint to the context
context_py = bpy.context.copy()
context_py["constraint"] = pose_bone.constraints["Child Of"]

# activate target bone
bpy.context.active_object.data.bones.active = pose_bone.bone 
bpy.ops.constraint.childof_set_inverse(context_py, constraint="Child Of", owner='BONE')

Reference

bpy.ops.constraint.apply
Childof_set_inverse

How To Setup ”Witchcraft and Wizardry” On The Server For Multi User

This is the log to setup Minecraft server and client to play “Witchcraft and Wizardry” map for multiplayer.

Though there is a detailed documents, I summarized my way to setup the server for beginners. Please note that we will not be liable for any damages caused by use of this add-on and scripts.

The environment

Minecraft Java Edition version 1.16.3 (Select Minecraft Java Edition 1.16 – 1.16.5)
CentOS Linux release 7.8.2003 (Core)
java version 1.8.0_332

I used rental VPS from ConoHa. You can use other rental servers , too.

Method

  1. Prepare the server
    1. Download server.jar
    2. Generate Minecraft vanilla data with server.jar
    3. Put “Witchcraft and Wizardry” files into Minecraft directory
    4. Change server settings
    5. Run
  2. Prepare the client
    1. Download resource.zip of “Witchcraft and Wizardry”
    2. Change the resource pack
    3. Access the server

1. Prepare the server

1.1 Download server.jar

If you have the vanilla server and the vanilla data, the default world data for Minecraft, on the server, you can skip section 1 and 2. Go to the step 3 Put “Witchcraft and Wizardry” files into minecraft directory!

There are 2 way to download, “download files on the local PC and upload” or “download files on the server directly.”

Download server.jar on the local PC and upload it

Download the server from mcversions.net. Select the version of your Minecraft and click the button “Download Server jar.” Be careful to select the correct version for your Minecraft!!

Then access the server with WinSCP. Generate “minecraft_server” directory and put the server.jar into the minecraft_server. Rename server.jar into minecraft_server.jar.

Download server.jar on the server directly with command

Access the server with Teraterm and download server.jar directly using “wget” command on the server. Be careful to select the correct version for your Minecraft!!

mkdir ~/opt/
cd opt
mkdir minecraft_server   # create directory where you'd like to setup server
cd minecraft_server

# this is the server for 1.16.3, check the link url on mcversions.net
wget https://launcher.mojang.com/v1/objects/f02f4473dbf152c23d7d484952121db0b36698cb/server.jar

mv server.jar minecraft_server.jar

1.2 Generate Minecraft vanilla data with server.jar

Run minecraft_server.jar

Then run the minecraft_server.jar, and the vanilla world, default world, is generated in “minecraft_server” directory. Remove all items in world directory.

java -Xmx1G -Xms1G -jar minecraft_server.jar nogui

stop # after generating minecraft data

If you are using Forge or fabric, put them on the minecraft_server directory instead of minecraft_server.jar. Be careful to select the correct version for your Minecraft!!

Reference: Setting up a Minecraft Forge server

1.3 Put “Witchcraft and Wizardry” files into Minecraft directory

There are 2 way to setup, “download files on the local PC and upload” or “download files on the server directly.”

Download “Witchcraft and Wizardry” on the local PC and upload it

Access the Floo Network page and download the map. I selected “Light version”.

Extract the downloaded zip.
Remove files in “world” directory on minecraft_server.
Then copy all files in the extracted directory “Witchcraft and Wizardry – Light” into the “world.”

Download “Witchcraft and Wizardry” on the server directly with command

Access the server with Teraterm and download server.jar directly using “wget” command.

mkdir ~/download_wichcraft
cd ~/download_wichcraft

wget http://download2391.mediafire.com/sqwru7rill4g/xke143473zi4ytp/Witchcraft+and+Wizardry+-+Light.zip
unzip Witchcraft+and+Wizardry+-+Light.zip -d Witchcraft_and_Wizardry

rm -r ~/opt/minecraft_server/world/
mkdir ~/opt/minecraft_server/world/ # remove all items from minecraft_server/world/

cp -r Witchcraft_and_Wizardry/* ~/opt/minecraft_server/world/  # copy all items into minecraft_server/world/

1.4 Change server settings

minecraft_server/eula.txt

eula=true

minecraft_server /server.propaties

enable-query=true
allow-flight=true
enable-command-block=true
resouce-pack-sha1=/home/username/Harry_Potter/1_server/resouces

1.5 Run

cd ~/opt/minecraft_server
java -Xmx1G -Xms1G -jar minecraft_server.jar nogui

You can run Forge or fabric, too.

# for Forge
java -server -Xms1G -Xmx1G -jar forge-1.16.3-34.1.0.jar

Prepare the client

Reference: Getting Started from Witchcraft And Wizardry Wiki

2.1 Download resource.zip of “Witchcraft and Wizardry”

Access the Floo Network page and download the map. I selected “Light version”.

Extract the downloaded zip.

2.2 Change the resource pack

Put resource.zip in your .minecraft/resourcepacks.

To change resource, start Minecraft and click Options > Resource Packs > resources.zip

Then the look changes as below.

2.3 Access the server

Click Multiplayer > Add server and put IP address of the server and any server name you like.

[Tips] How To Resize Image In markdown

In markdown documents such as GitHub, there are 2 style of putting image.

![alternate text](url/to/image.jpg"Image Title")

<img src="url/to/image.jpg" alt="alternate text" title="Image Title">

Use the latter style to resize the image as below.

<img src="url/to/image.jpg" alt="alternate text" title="Image Title" width="300" height="200">

[Trouble Shooting] NullFunctionError of glutInit in OpenGL

Problem

When trying to call “glutInit()” of PyOpenGL, I got the error “NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling”.

# python source code
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) 
 
Error Detail

---------------------------------------------------------------------------
NullFunctionError                         Traceback (most recent call last)
/tmp/ipykernel_14/3289264930.py in <module>
      3 from OpenGL.GLU import *
      4 
----> 5 glutInit()
      6 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
      7 

/usr/local/lib/python3.9/site-packages/OpenGL/GLUT/special.py in glutInit(*args)
    331     try:
    332         # XXX need to check for error condition here...
--> 333         _base_glutInit( ctypes.byref(count), holder )
    334     finally:
    335         os.chdir( currentDirectory )

/usr/local/lib/python3.9/site-packages/OpenGL/platform/baseplatform.py in __call__(self, *args, **named)
    421                 pass
    422             else:
--> 423                 raise error.NullFunctionError(
    424                     """Attempt to call an undefined function %s, check for bool(%s) before calling"""%(
    425                         self.__name__, self.__name__,

NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling

Environment

Windows10
Python 3.9.7

Cause

There are some Recommended Enhancements for PyOpenGL. And some of them, such as GLUT or FreeGLUT, are not contained in PyOpenGL itself.

Solution

Solution1 use binary installer for windows.

The documentation says “Win32 and Win64 binary installers for PyOpenGL include a copy of GLUT”.
So uninstall current pyopengl first.
And download binary installer for windows. Put the downloaded file in some directory, then run the command “pip install <file name>” in the directory where the file is saved.

pip uninstall PyOpenGL
pip install PyOpenGL‑3.1.6‑cp39‑cp39‑win_amd64.whl

Solution2 install GLUT or FreeGLUT separately

Installing and adding GLUT or FreeGLUT to PATH solves this problem.

Build FreeGLUT from source code or download built FreeGLUT from “Download freeglut 3.0.0 for MSVC” in transmissionzero.co.uk/software/freeglut-devel.

Put freeglut\bin\x64\freeglut.dll into C:\Windows\System32.

Add “C:\Windows\System32” to environment variable “PATH” to enable python find the library.

If the error still occurred, check if your library name is in Win32Platform.GLUT() <python>\Lib\site-packages\OpenGL\platform\win32.py

    @baseplatform.lazy_property
    def GLUT( self ):
        for possible in ('freeglut%s.%s'%(size,vc,), 'freeglut', 'glut%s.%s'%(size,vc,)):  # Added 'freeglut' because the library name is freeglut.dll
            # Prefer FreeGLUT if the user has installed it, fallback to the included 
            # GLUT if it is installed
            try:
                return ctypesloader.loadLibrary(
                    ctypes.windll, possible, mode = ctypes.RTLD_GLOBAL
                )
            except WindowsError:
                pass
        return None

These links might help you.
python – Attempt to call an undefined function glutInit
#219 glutInit fails on windows 64-bit
Attempt to call an undefined function glutInit
Python and PyOpenGL Installation

Appendix: How to install GLUT or FreeGLUT on Linux

Use “sudo apt-get install python-opengl” command to install PyOpenGL with dependent library at once.

How To Get Mapping of UV and Vertex

GOAL

To get correspondence of UV coordinates and vertex id in the object in Blender scene by Blender Python. The following is output of the script.

uv: 0.625 0.5 vertex id: 0
uv: 0.875 0.5 vertex id: 4
uv: 0.875 0.75 vertex id: 6
uv: 0.625 0.75 vertex id: 2
uv: 0.375 0.75 vertex id: 3
.
.
.

Environment

Blender 2.83 (Python 3.7.4)
Windows 10

Method

Mesh Loop

Use Mesh Loop to get UV and vertex data.

In unfolded UV, the correspondence between the point of UV map and the vertex of 3D object is not one-to-one. Thus we use ‘Mesh Loop’ instead of vertex or edge to distinct point of UV map.

Mesh Loop is an element surrounding a face, which consists of edges and vertices. Each quad face consists of 4 Mesh Loops as below. For example, cube objects have 6face, 24 mesh loops.

import bpy

obj = bpy.data.objects[obj_name]
mesh_loops = obj.data.loops 
for mesh_loop in mesh_loops:
    print(mesh_loop)

Mesh UV Loop

UVs have Mesh UV Loops as a counterpart to the Mesh Loops. And the correspondence between Mesh Loop and MeshUVLoop is one-to-one.

import bpy

obj = bpy.data.objects[obj_name]
mesh_uv_loop = obj.data.uv_layers[0].data[loop_index]

Source Code

import bpy

def get_uvs(obj_name):
    obj = bpy.data.objects[obj_name]
    mesh_loops = obj.data.loops

    for i, mesh_loop in enumerate(mesh_loops):
        mesh_uv_loop = obj.data.uv_layers[0].data[i]
        print("uv:", mesh_uv_loop.uv[0], mesh_uv_loop.uv[1], "vertex id:", mesh_loop.vertex_index)

get_uvs("Cube")

How To Start Anaconda

GOAL

Today’s goal is to construct development environment for data analytics and machine learning with Anaconda.

What is Anaconda?

Anaconda is open source Python distribution for data science. You can see the list of package lists here.

the open-source Individual Edition (Distribution) is the easiest way to perform Python/R data science and machine learning on a single machine. Developed for solo practitioners, it is the toolkit that equips you to work with thousands of open-source packages and libraries.

from anaconda.com/products/individual

Environment

macOS Catalina 10.15.5
Python 3.9.7

Method

Download & Install

Access the websiteanaconda.com/products/individual and click “Download” button to download the installer of the edition that you want.

Start the installer and click “Continue”.

Check if anaconda is completely installed with terminal.

Start Anaconda Navigator

Start applications > Anaconda-Navigator.

Create virtual environment

Click Environments and create new environment.

I named new environment “data_analysis”.

Install libraries or modules with conda

Conda is an open source package management system and environment management system.

Open terminal in the environment where you want to install libraries.

Then put the “conda install” command to install libraries.
For example, I installed pytorch in the “pytorch” environment. The option “-c” is the channel (What is a “conda channel”?).

conda install pytorch torchvision -c pytorch

Start Application

Select environment what you want to use and install or launch application.

I launched “Jupyter notebook” and check that “pythorch” library is installed successfully.

How To Import Another Blender File

GOAL

Today’s goal is to show how to import data from another blender file.

We can import .fbx, .obj and so on by “menu File>import”, but how can we import .blend file to current scene?

The way to import fbx file

I have 2 blender scene and want to import scene_from.blend to scene_to.blend directly.

Environment

Blender2.83(LTS)
Windows 10

Method

Click File>Append

Double click the scene you want to import. Then select what you want. In my case, I imported collection that contains all objects.

Result of “Append”

The objects in scene_from.blend is imported to scene_to.blend with their materials.

Supplement

Link

You can use File>Link too, but the result is different.

Result of “Link”

You can’t modify linked objects in scene_to.blend. If you’d like to modify the object, change the scene_from.blend.

What Is Convolution In Neural Network?

GOAL

Today’s goal is to understand a layer of process “convolution” in neural network. In other words, this article describes convolutional neural network (CNN or ConvNet) that is a neural network contains convolutional layers in its architecture.

What Convolution Is

Convolution is the binary operation to takes 2 functions and produces a function \(f * g\), which is defined as the integral of the product of the two functions after one is reversed and shifted.

$$(f*g)(t) = \int f(\tau)g(t – \tau)d\tau $$

Examples of 2 function

In the context of image processing, convolution is the process of generating output image by weighting input image with the filter. For example, convolution is used in smoothing with gaussian filter.

Example of convolution by Gaussian filter

The image of weights is called “kernel” in convolution. And the output is the compression of input.

In CNN, the convolution layer is used to generate output image that represents feature of input image while compressing local region. 1 layer can have several kernels and the output is the same number of feature maps as kernels.

Architecture of CNN
by Aphex34

Details Of Convolution Layer

In convolution layer, the input image will be converted. For example, a 5*5 kernel is applied to RGB 32*32 image to generate 28*28 output as below.

Note that there are 2 styles of convolution for RGB image. The first one is the way in which 3 maps generated from RGB channels by convolution are added together to 1 channel output image. In the second way, each channel is converted to each channel of output image. In the latter case the output image has 3 channels.

The former is commonly used in CNN.

If the convolution layer has 5 different kernels, the output has 5 channels.

Parameters

Parameters that determines convolution process.

  • channel
  • kernel size
  • stride
  • padding
  • dilation

Channel and kernel size

channel = input channel * the number of kernel. The channel of output is the same as the channel of kernel.

Kernel size is the size of kernel side.

Stride

Stride is the size that filter sliding to input image.

Padding

Padding is the amount of padding space applied on both sides of input. Padding changes output size to fit input image size.

Dilation

Dilation controls the spacing between the kernel points.

Convolution In PyTorch

PytTorch provides a method torch.nn.Conv2d() for 2D convolution. Conv2d makes a convolutional layer in network class that extends nn.Module as below.

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
  def __init__(self):
    super(Net, self).__init__()
    self.conv1 = nn.Conv2d(1, 6, 3) #1channel input, 6channel output (6kernels), 3*3 kernel
    self.conv2 = nn.Conv2d(6, 16, 3) #6channel input, 16channel output, 3*3 kernel 

    self.fc1 = nn.Linear(16 * 6 * 6, 120) #Linear transform from 16*6*6 features into 84 features
    self.fc2 = nn.Linear(120, 84)
    self.fc3 = nn.Linear(84, 10)

  def forward(self, x):
    x = F.relu(self.conv1(x))
    x = F.max_pool2d(x, (2, 2))
    x = F.relu(self.conv2(x))
    x = F.max_pool2d(x, 2)
    x = x.view(-1, self.num_flat_features(x))
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x

  def num_flat_features(self, x):
    size = x.size()[1:]
    num_features = 1
    for s in size:
      num_features *= s
    return num_flat_features

net = Net()

See the detail of net architecture by print().

print(net)

——outout——
Net(
  (conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
  (fc1): Linear(in_features=576, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)

See the size of parameters in conv1 and conv2.

params = list(net.parameters())
print(params[0].size())
print(params[2].size())

——outout——
torch.Size([6, 1, 3, 3])
torch.Size([16, 6, 3, 3])

How To Embed Inline Mathematical Formula In WordPress

GOAL

Today’s goal is to summarize how to embed inline formula such as \( f(x)=\sqrt{x^2}\) using plugin “MathJax-LaTeX” in WordPress.

If you haven’t installed “MathJax-LaTeX” yet, add the plug-in and activate it. Check the related article “How To Post Formula on Your WordPress Website”.

Environment

  • WordPress 5.8.2
  • MathJax-LaTeX 1.3.11

mathjax

Method

Inline formula

Put formula [latex] f(x)=\sqrt{x^2} [/latex] as a test.

Put formula \( f(x)=\sqrt{x^2} \) as a test.

Put formula \( f(x)=\sqrt{x^2} \) as a test.

Put formula \( f(x)=\sqrt{x^2} \) as a test.

Block formula

Put formula $$ f(x)=\sqrt{x^2} $$ as a test.

Put formula $$ f(x)=\sqrt{x^2} $$ as a test.

Put formula \[ f(x)=\sqrt{x^2} \] as a test.

Put formula \[ f(x)=\sqrt{x^2} \] as a test.